数据库 
首页 > 数据库 > 浏览文章

SQL Server 通过with as方法查询树型结构

(编辑:jimmy 日期: 2024/5/16 浏览:3 次 )

一、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'%/%'

SQL Server 通过with as方法查询树型结构

还能通过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)

SQL Server 通过with as方法查询树型结构

好了这篇文章就介绍到这了,希望能帮助到你。

上一篇:SqlServer 数据库 三大  范式
下一篇:SQL Server中with as使用介绍
一句话新闻
高通与谷歌联手!首款骁龙PC优化Chrome浏览器发布
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网