使用 apply 運(yùn)算符可以為實(shí)現(xiàn)查詢操作的外部表表達(dá)式返回的每個(gè)行調(diào)用表值函數(shù)。表值函數(shù)作為右輸入,外部表表達(dá)式作為左輸入。通過(guò)對(duì)右輸入求值來(lái)獲得左輸入每一行的計(jì)算結(jié)果,生成的行被組合起來(lái)作為最終輸出。apply 運(yùn)算符生成的列的列表是左輸入中的列集,后跟右輸入返回的列的列表。 
apply 有兩種形式: cross apply 和 outer apply。cross apply 僅返回外部表中通過(guò)表值函數(shù)生成結(jié)果集的行。outer apply 既返回生成結(jié)果集的行,也返回不生成結(jié)果集的行,其中表值函數(shù)生成的列中的值為 null。
 --創(chuàng)建test表
--創(chuàng)建test表 create table test(oid int,name char(20),lead char(10))
create table test(oid int,name char(20),lead char(10))
 --往里面插入幾行數(shù)據(jù)
--往里面插入幾行數(shù)據(jù) insert into test values(1,'測(cè)試公司','11')
insert into test values(1,'測(cè)試公司','11') insert into test values(1,'測(cè)試公司','12')
insert into test values(1,'測(cè)試公司','12') insert into test values(1,'測(cè)試公司','13')
insert into test values(1,'測(cè)試公司','13') insert into test values(1,'測(cè)試公司','14,15,16')
insert into test values(1,'測(cè)試公司','14,15,16')

 --拆分字符串函數(shù)
--拆分字符串函數(shù) alter function select_dempart_manager
alter function select_dempart_manager (
( @oid int,
@oid int, @lead char(10)
@lead char(10) )
) returns @temp table(oid int,lead char(10))
returns @temp table(oid int,lead char(10)) as
as begin
begin while charindex(',',@lead)>1
   while charindex(',',@lead)>1 begin
     begin insert into @temp values(@oid,left(@lead,charindex(',',@lead)-1))
       insert into @temp values(@oid,left(@lead,charindex(',',@lead)-1)) set @lead=stuff(@lead,1,charindex(',',@lead),'')
       set @lead=stuff(@lead,1,charindex(',',@lead),'') end
     end insert into @temp values(@oid,@lead)
   insert into @temp values(@oid,@lead)    return
return end
end
 --使用apply函數(shù)調(diào)用
--使用apply函數(shù)調(diào)用 select a.oid,name,st.lead from test a
select a.oid,name,st.lead from test a outer apply select_dempart_manager(a.oid,a.lead) as st
outer apply select_dempart_manager(a.oid,a.lead) as st
 --結(jié)果
--結(jié)果 --oid name                    lead
--oid name                    lead --1    測(cè)試公司               11
--1    測(cè)試公司               11         --1    測(cè)試公司               12
--1    測(cè)試公司               12         --1    測(cè)試公司               13
--1    測(cè)試公司               13         --1    測(cè)試公司               14
--1    測(cè)試公司               14         --1    測(cè)試公司               15
--1    測(cè)試公司               15         --1    測(cè)試公司               16
--1    測(cè)試公司               16        
 
新聞熱點(diǎn)
疑難解答
圖片精選