自定义函数:根据自己的需要,自定义一些函数 自定义函数分为三类:

    • 标量函数:对单一值的操作,返回单一值,用begin end包括起来
    • 内嵌表值函数:是一种参数化的视图,返回一个表,没有begin end包括起来
    • 多声明表值函数:返回的也是一个表,用begin end包括函数体,是标量函数和内嵌表值函数的结合体
    1. --标量函数:返回唯一值 用于查询
    2. create function [dbo].GetUserAge(@UserId int)
    3. --create function [dbo].GetUserAge(@UserId int=2) --参数中设置默认值
    4. returns int
    5. --with encryption 用于函数加密
    6. as
    7. begin
    8. declare @age int
    9. select @age=Age from UserInfos where UserId = @UserId
    10. return @age
    11. end
    12. go
    13. --函数调用
    14. select dbo.GetUserAge(3) as 年龄
    15. select dbo.GetUserAge(default) as 年龄 --调用的时候用default
    16. --注意点:
    17. --1.创建标量函数的时候,如果指定了所有者,调用的时候也必须指定函数所有者
    18. --2.调用时,如果函数中指定了默认值,调用时参数用default替代,如果函数中没有默认值,调用时使用default则返回null
    19. --3.语法上:returns 返回值类型 return 表达式/值
    20. --4.begin end 中间不能有修改数据的操作
    1. --内嵌表值函数
    2. create function [dbo].GetUserInfo(@userId int)
    3. returns table
    4. as
    5. return(
    6. select UserId,UserName,Age,DeptId from UserInfos
    7. where UserId=@userid
    8. )
    9. go
    10. --调用函数
    11. select * from dbo.GetUserInfo(27)
    12. 注意点:
    13. 1.returns table --只能跟table
    14. 2.as 后面没有begin end 只能是return select(select语句)
    1. --多语句表值函数
    2. create function [dbo].SearchUsers(@uName varchar(50))
    3. returns @users table(
    4. Id int not null primary key,
    5. name varchar(50) not null,
    6. age int null
    7. )
    8. as
    9. begin
    10. --函数体
    11. insert into @users(Id,name,age)
    12. select UserId,UserName,Age from UserInfos
    13. where UserName like '%'+@uName+'%'
    14. return --后面什么也不跟
    15. end
    16. go
    17. --调用
    18. select * from dbo.SearchUsers('lqq')
    19. 注意点:
    20. 1.创建标量函数的时候,如果指定了所有者,调用的时候也必须指定函数所有者
    21. 2.return --后面什么也不跟
    22. 3.函数一般用作查询使用,不能用于数据修改
    23. 4.如果用内嵌表值函数能满足需求,就不要使用多语句表值函数