一、with as 公用表表达式
类似view,但是不并没有创建对象,with as 公用表表达式不创建对象,只能被后随的select语句,其作用:
1. 实现递归查询(树形结构)
2. 可以在一个语句中多次引用公用表表达式,使其更加简洁
二、非递归的公共表达式
可以是定义列或自动列和select into 效果差不多
--指定列 with withtmp1 (code,cname) as ( select id,name from classunis ) select * from withtmp1 --自动列 with withtmp2 as ( select * from classunis where author = 'system' ) select * from withtmp2
三、递归的方式
通过union all 连接部分。通过连接自身whit as 创建的表达式,它的连接条件就是递归的条件。可以从根节点往下查找,从子节点往父节点查找。只需要颠倒一下连接条件。例如代码中条件改为t.id = c.parentid即可
with tree as( --0 as level 定义树的层级,从0开始 select *,0 as level from classunis where parentid is null union all --t.level + 1每递归一次层级递增 select c.*,t.level + 1 from classunis c,tree t where c.parentid = t.id --from classunis c inner join tree t on c.parentid = t.id ) select * from tree where author not like'%/%'
还能通过option(maxrecursion number) 设置最大递归次数。例如上诉结果level 最大值为2表示递归两次。我们设置其值为1
with tree as( select *,0 as level from classunis where parentid is null union all select c.*,t.level + 1 from classunis c,tree t where c.parentid = t.id ) select * from tree where author not like'%/%' option(maxrecursion 1)
好了这篇文章就介绍到这了,希望能帮助到你。