sql server 2005中使用apply对每行调用表值函数

80酷酷网    80kuku.com

  server|函数

使用 APPLY 运算符可以为实现查询操作的外部表表达式返回的每个行调用表值函数。表值函数作为右输入,外部表表达式作为左输入。通过对右输入求值来获得左输入每一行的计算结果,生成的行被组合起来作为最终输出。APPLY 运算符生成的列的列表是左输入中的列集,后跟右输入返回的列的列表。

APPLY 有两种形式: CROSS APPLY OUTER APPLYCROSS APPLY 仅返回外部表中通过表值函数生成结果集的行。OUTER APPLY 既返回生成结果集的行,也返回不生成结果集的行,其中表值函数生成的列中的值为 NULL

--创建test表
create table test(oid int,name char(20),lead char(10))

--往里面插入几行数据
insert into test values(1,'测试公司','11')
insert into test values(1,'测试公司','12')
insert into test values(1,'测试公司','13')
insert into test values(1,'测试公司','14,15,16')


--拆分字符串函数
alter function select_Dempart_Manager
(
oid int,
lead char(10)
)
returns temp table(oid int,lead char(10))
as
begin
   
while charindex(',',lead)>1
     
begin
       
insert into temp values(oid,left(lead,charindex(',',lead)-1))
       
set lead=stuff(lead,1,charindex(',',lead),'')
     
end
   
insert into temp values(oid,lead)   
return
end

--使用apply函数调用
select a.oid,name,ST.lead from test a
outer apply select_Dempart_Manager(a.oid,a.lead) as ST

--结果
--
oid name                    lead
--
1    测试公司               11        
--
1    测试公司               12        
--
1    测试公司               13        
--
1    测试公司               14        
--
1    测试公司               15        
--
1    测试公司               16        



分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: