自定义函数分为两大类,即标量函数和表值函数.
标量函数就是返回标量值的函数.比较容易理解.
表值函数就是返回一个表.可以起到视图的作用,但是又比视图的功能强大,因为视图无法指定where条件,可是表值函数就非常灵活.--创建员工表
create table test (
姓名 varchar(10),
部门 char(2),
工资 numeric(8,2),
)insert into test 
select '刘德华','01',980 
union all  select '张学友','01',1200
union all  select '李汶','02',1980
union all  select '张信哲','02',980
union all  select '刘欢','03',567
union all  select '孙楠','03',1133
union all  select '王菲','04',3456
union all  select '张国立','03',786
union all  select '李连杰','04',2155--查看表记录
select *
from testgo--创建部门表
create table bm (
部门 char(2),
部门名称 varchar(10)
)insert into bm
select '01','人事部' 
union all select '02','财务部'
union all select '03','生产部'
union all select '04','销售部'go--创建内嵌表值函数
create function fn_bumen
(@bm char(2))
returns table
as 
return (
select * 
from test
where 部门=@bm
)
--调用自定义函数
select *
from fn_bumen('02')
--结果如下:
/*
姓名         部门   工资         
---------- ---- ---------- 
李汶         02   1980.00
张信哲        02   980.00(所影响的行数为 2 行)
*/go--创建多语句表值函数
create function fn_salary ( @bm char(2) )
returns @salary table
   (
    姓名     varchar(10),
    部门名称 varchar(10),
    工资       numeric(8,2)
   )
as
begin
   insert @salary
        select a.姓名,b.部门名称,a.工资
        from test a left join bm b 
              on a.部门=b.部门
        where a.部门=@bm
   return
end--调用fn_salary
select *
from fn_salary('02')--结果如下:
/*
姓名         部门名称       工资         
---------- ---------- ---------- 
李汶         财务部        1980.00
张信哲        财务部        980.00(所影响的行数为 2 行)
*/