使用APPLY运算符可以实现查询操作的外部表表达式返回的每个调用表值函数。表值函数作为右输入,外部表表达式作为左输入。
通过对右输入求值来获得左输入每一行的计算结果,生成的行被组合起来作为最终输出。APPLY 运算符生成的列的列表是左输入
中的列集,后跟右输入返回的列的列表。
APPLY存在两种形式: CROSS APPLY 和 OUTER APPLY .
CROSS APPLY 仅返回外部表中通过表值函数生成结果集的行。
OUTER APPLY 既返回生成结果集的行,又返回不生成结果集的行,其中表值函数生成的列中的值为NULL.
create table employee
(
emp_id int not null,
mgr_id int null,
emp_name varchar(20) not null,
emp_salary money not null,
constraint pk_id primary key(emp_id)
)
insert into employee select 1,null,‘忘忘‘,4500
union all
select 2,1,‘找找‘,2500
union all
select 3,2,‘你会‘,3500
union all
select 4,3,‘牛牛‘,1500
union all
select 5,4,‘得到‘,500
union all
select 6,5,‘爱的色放‘,300
union all
select 7,6,‘爱上对方‘,1000
union all
select 8,4,‘阿萨德‘,300
union all
select 9,8,‘阿斯顿‘,1000
create table departments
(
dep_id int identity(1,1) primary key,
dep_name varchar(30) not null,
dep_m_id int null references employee(emp_id)
)
insert departments select ‘生成部门‘,2
union all
select ‘销售部门‘,7
union all
select ‘加工部门‘,8
union all
select ‘库存部门‘,9
union all
select ‘管理部门‘,4
union all
select ‘保卫部门‘,null
create function gtree
(
@emp_id int
)
returns @tree table
(
emp_id int not null,
emp_name varchar(20) not null,
mgr_id int null,
lvl int not null
)
as
begin
with emp_subtree(emp_id,emp_name,mgr_id,lvl)
as
(
select emp_id,emp_name,mgr_id,0 from employee where [email protected]_id
union all
select e.emp_id,e.emp_name,e.mgr_id,es.lvl+1
from employee e join emp_subtree es on e.emp_id=es.emp_id
)
insert @tree select * from emp_subtree
return
end
select * from employee
select * from departments as a
cross apply
gtree(a.dep_m_id) as b
select * from departments as a
outer apply
gtree(a.dep_m_id) as b