使用 apply 运算符可以为实现查询操作的外部表表达式返回的每个行调用表值函数。表值函数作为右输入,外部表表达式作为左输入。通过对右输入求值来获得左输入每一行的计算结果,生成的行被组合起来作为最终输出。apply 运算符生成的列的列表是左输入中的列集,后跟右输入返回的列的列表。 
apply 有两种形式: cross apply 和 outer apply。cross 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        
新闻热点
疑难解答