博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
cross apply 和 outer apply
阅读量:7096 次
发布时间:2019-06-28

本文共 1629 字,大约阅读时间需要 5 分钟。

使用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

转载地址:http://enhql.baihongyu.com/

你可能感兴趣的文章
iptables
查看>>
.NET自动识别GB2312与UTF-8编码的文件
查看>>
Linux下apache日志分析与状态查看方法
查看>>
hdu2412(树形dp)
查看>>
js返回函数, 函数名后带多个括号的用法及join()的注意事项
查看>>
【NOIP2007】矩阵取数
查看>>
关于VIM在Win10下的无意义折腾
查看>>
ibatis example Class 使用
查看>>
android的触摸事件(转)
查看>>
springMVC与struts2的区别
查看>>
【DB2数据库在windows平台上的安装】
查看>>
课后作业-阅读任务-阅读笔记-4
查看>>
Yii2数据缓存详解
查看>>
02Scala-函数定义、流程控制、异常处理入门实战
查看>>
jquery,smarty,dedecms的插件思路------dede未实践
查看>>
php pdo错误:SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
查看>>
Team Foundation Server:CodeUI Automation Test 学习笔记4
查看>>
Linux 小知识翻译 - 「cron」
查看>>
docker 一些简略环境搭建及部分链接
查看>>
android studio获取SHA1
查看>>