create function [拥有者.] 函数名
([@参数名 as 标量数据类型 [=default]])
returns 返回变量 table<表定义>
[as]
begin
函数体
return
end
1、标量函数
标量函数是返回单个数据值的函数。
create function [拥有者.] 函数名
([{@参数名 [as] 标量数据类型 [=default]}])
returns 返回值类型
[as]
begin
函数体
return 标量表达式
end
说明:
1)同存储过程一样,函数的参数也可以有默认值。如果函数的参数有默认值,则在调用该函数时必须指定"default"关键字。这与存储过程的有默认值参数的使用略有不同,在存储过程中省略参数则意味着使用默认值。
2)标量表达式:指定标量函数返回的标量值(即单个数据值)
标量函数返回在returns子句中定义的类型的单个数据值。标量函数的返回值类型不能是大文本、图像等类型。
如:
create function dbo.f_GoodsCount (@class varchar(10))
returns int
as
begin
declare @x int
select @x=count(*) from table_GoodsClass a join Table_Goods b on a.GoodsClassID=b.GoodsClassID where GoodsClassName=@class
return @x
end
select GoodsName as 商品名,dbo.f_GoodsCount('服装') as 种类数 from Table_GoodsClass a join Table_Goods b on a.GoodsClassID=b.GoodsClassID where GoodsClassName='服装' --调用用户自己定义的函数
2、内嵌表值函数
内嵌表值函数的返回值是一个表,该表的内容是一个查询语句的结果。
create function [拥有者.] 函数名
([@参数名 as 标量数据类型[=default]])
returns table
[as]
return [(]select 语句[)]
在内嵌表值函数中,通过单个select 语句定义返回的table值。内嵌函数没有相关联的返回变量,也没有函数体。
如:
create function f_GoodsInfo(@class char(10))
returns table
as
return (
select GoodsName,SaleUnitPrice from Table_GoodsName a join Table_Goods b on a.GoodsClassID=b.GoodsClassID
where GoodsClassName=@class
)
select * from dbo.f_GoodsInfo('服装') --调用内嵌表值函数
3、多语句表值函数
如:
create function f_GoodsType(@class varchar(20))
returns @t_GoodsType table(
商品名 varchar(50),
单价 money,
生产日期 datetime,
类型 varchar(10)
)
as
begin
insert into @t_GoodsType
select GoodsName,SaleUnitPrice,ProductionDate,case
when datediff(month,ProductionDate,'2012/2/10')>12 then '旧商品'
when datediff(month,ProductionDate,'2012/2/10') between 6 and 12 then '一般商品'
when datediff(month,ProductionDate,'2012/2/10')<6 then '新商品'
end
from Table_GoodsClass a join Table_Goods b on a.GoodsClassID=b.GoodsClassID
where GoodsClassName=@class
end
在定义函数时也可以调用已经定义好的函数。
select * from dbo.f_GoodsType('家用电器')