1、函数的种类
标量函数:返回一个值的函数
内嵌表函数:返回一个表,多行多列,只能写Select语句
多语句函数:是一种受限的T_SQL ,可以写 while if语句。受限表现在:在增删改方面:只能对返回的表进行增删改,不能对别的表进行增删改。
For example 1:
create function fn_age (@ageadd int)
returns int
as
begin
declare @age int
declare @ageresult int
set @age=@ageadd+1
select @ageresult=avg(age) from lucy where age like @age
return @ageresult
end
//执行,看一下结果
select dbo.fn_age(20) as result(指明列名)
For example2:
Create function 函数名(参数)
Returns 返回值数据类型
[with {Encryption | Schemabinding }]
[as]
begin
SQL 语句( 必须有return 变量或值)
End
Schemabinding : 将函数绑定到它引用的对象上(注:函数一旦绑定,则不能删除、修改,除非删除绑定)
Create function AvgResult(@scode varchar(10))
Returns real
As
Begin
Where scode like @code
Return @avg
End
执行用户自定义函数
select 用户名。函数名 as 字段别名
select dbo.AvgResult(‘s0002’) as result
用户自定义函数返回值可放到局部变量中,用set ,select,exec 赋值
declare @avg1 real ,@avg2 real ,@avg3 real
select @avg1= dbo.AvgResult(‘s0002’)
set @avg2= dbo.AvgResult(‘s0002’)
exec @avg3= dbo.AvgResult ‘s0002’
select @avg1 as avg1 ,@avg2 as avg2 ,@avg3 as avg3
函数引用
create function code(@scode varchar(10))
returns varchar(10)
as
begin
declare @ccode varchar(10)
set @scode = @scode + ‘%’
select @ccode=ccode from cmessage
return @ccode
end
select name from class where ccode = dbo.code(‘c001’)