函数

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('家用电器')


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈极简

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值