create function [函数的所有者].函数名(标量参数 [as] 标量参数类型 [=默认值])
returns 标量返回值类型
[with {Encryption | Schemabinding }]
[as]
begin
函数体(即 Transact-SQL 语句)
return 变量/标量表达式
end
下面自定义一个根据传入参数(即学生性别)来计算学生平均身高的 Function,示例如下:
use Test
go
create function dbo.AvgHeight(@Sex varchar(10)='男')
returns decimal
as
begin
declare @AvgHeight decimal(10,2)
select @AvgHeight=AVG(Convert(decimal(10,2),S_Height)) from Student where S_Sex=@Sex
return @AvgHeight
end
go
执行用户自定义标量函数:
use Test
go
create function dbo.SearchStuInfo(@Stu_No varchar(50)='001')
returns table
as
return(
select S_StuNo,S_Name,S_Sex,S_Height,S_BirthDate
from Student where S_StuNo=@Stu_No)
go
执行用户自定义内嵌表值函数:
select * from dbo.SearchStuInfo(default);
select * from dbo.SearchStuInfo('008');
创建多声明表值函数的语法:
create function [函数的所有者].函数名(标量参数 [as] 标量参数类型 [=默认值])
returns @表变量 table 表的定义(即列的定义和约束)
[with {Encryption | Schemabinding }]
[as]
begin
函数体(即 Transact-SQL 语句)
return
end
下面自定义一个根据传入参数(即学生学号)来查询学生信息和课程,并计算出该学生的身高是否大于所有学生的平均身高的 Function,示例如下:
use Test
go
create function dbo.SearchStuCou(@StuN varchar(10)='001')
returns @StuInfo table (
StuNo varchar(50) not null primary key,
StuName varchar(10) not null,
StuSex varchar(10) not null,
StuHeight varchar(10) null,
StuAvgHeight decimal(10,2) null,
StuConAvgHeight varchar(30) null,
StuCou varchar(10) null
)
as
begin
declare @Height decimal(10,2)
declare @AvgHeight decimal(10,2)
declare @ConAvgHeight varchar(30)
select @AvgHeight=AVG(Convert(decimal(10,2),S_Height))
from Student
select @Height=Convert(decimal(10,2),S_Height)
from Student
where S_StuNo=@StuN
if((@Height-@AvgHeight) > Convert(decimal(10,2),0))
begin
set @ConAvgHeight='大于平均身高'
end
else if((@Height-@AvgHeight) = Convert(decimal(10,2),0))
begin
set @ConAvgHeight='等于平均身高'
end
else
begin
set @ConAvgHeight='小于平均身高'
end
insert into @StuInfo(StuNo,StuName,StuSex,StuHeight,StuAvgHeight,StuConAvgHeight,StuCou)
select s.S_StuNo,s.S_Name,s.S_Sex,s.S_Height,@AvgHeight,@ConAvgHeight,c.C_Name from Student s
left join Course c on s.C_S_Id=c.C_Id
where S_StuNo=@StuN
return
end
go
执行用户自定义多声明表值函数: