SQLServer中的函数定义与使用

一、标量函数

  • 语法:

    create function 拥有者.函数名(标量参数 as 标量数据类型)
    returns 返回参数数据类型
    as
    begin
    函数体
    return 变量//标量表达式
    end
    
  • 案例:

    USE [RW_TEST]
    GO
    /****** Object:  UserDefinedFunction [dbo].[StudentFunc]    Script Date: 2022/12/19 9:19:07 ******/
    /*
    根据参数ID,获取学生的手机号码:
    调用:
    
    declare @bmrs char(11)
    select @bmrs=  dbo.StudentFunc(2)
    select '手机号码为:'=@bmrs
    go
    */
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE function [dbo].[StudentFunc](@bmh as int)
    returns char(11)
    as
    begin
    
    declare @bmrs char(11)
    select @bmrs= phone_number from StudentsA where id=@bmh
    return @bmrs
    
    end
    
    
    

二、内嵌表值函数

  • 语法:

    create function 函数所有者.函数名称(标量参数 as 标量参数数据类型)
    
    returns table
    
    as
    
    return (select语句)
    
  • 案例:

    USE [RW_TEST]
    GO
    /****** Object:  UserDefinedFunction [dbo].[StudentFunc2]    Script Date: 2022/12/19 10:20:31 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    /*
    功能描述:
    查询ID大于输入参数值的学生信息
    调用:
    SELECT * FROM dbo.StudentFunc2(1)
    */
    GO
    ALTER function [dbo].[StudentFunc2](@bmmc  as int)
    returns table 
    as
    return (SELECT * FROM StudentsA WHERE ID > @bmmc)
    
    

三、多语句表值函数

  • 语法:

    create function [所有者名称.]函数名称(@参数名称 as 标量数据类型)
    returns @表变量 table 表的定义
    as
    
    begin
    函数体
    return
    end
    
    go
    
  • 案例:

    USE [RW_TEST]
    GO
    /****** Object:  UserDefinedFunction [dbo].[StudentPhoneInfo]    Script Date: 2022/12/19 10:46:21 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    /*
    调用:
    SELECT * FROM dbo.StudentPhoneInfo(0)
    */
    
    ---创建多语句表值函数
    ALTER function [dbo].[StudentPhoneInfo](@stuId as int)
    
    returns @StuPhoneNumber
    table( 
    	[name] [nchar](10) NULL,
    	[phone_number] [char](11) NULL
    )
    as
    
    begin
    
    declare @StuAge
    table( 
    	[name] [nchar](10) NULL,
    	[age] [int] NULL
    )
    
    ---查询并插入资料
    if(@stuId > 0)
    	begin
    	insert @StuPhoneNumber select name,phone_number from StudentsA where id =@stuId
    	insert @StuAge select name,age from StudentsA where id =@stuId
    	end
    
    else 
    	begin
    	insert @StuPhoneNumber select name,phone_number from StudentsA  
    	insert @StuAge select name,age from StudentsA  
    	end
    
    return
    
    end
    
    
    
posted @ 2022-12-19 10:49  码农阿亮  阅读(321)  评论(0)    收藏  举报