cross apply 和 outer apply

使用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  emp_id=@emp_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
 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值