SQLServer如何通过withas方法查询树型结构

SQL Server如何通过with as方法查询树型结构,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

成都创新互联从2013年开始,先为淮阴等服务建站,淮阴等地企业,进行企业商务咨询服务。为淮阴企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

一、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)

关于SQL Server如何通过with as方法查询树型结构问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


文章名称:SQLServer如何通过withas方法查询树型结构
URL地址:http://bzwzjz.com/article/ghephd.html

其他资讯

Copyright © 2007-2020 广东宝晨空调科技有限公司 All Rights Reserved 粤ICP备2022107769号
友情链接: 响应式网站建设 成都网站制作 营销型网站建设 成都网站建设 重庆电商网站建设 成都网站建设流程 成都网站建设 成都网站建设 高端网站设计 成都网站建设 重庆外贸网站建设 成都网站建设 成都网站设计 企业网站建设 成都品牌网站设计 H5网站制作 外贸网站设计方案 品牌网站建设 定制网站建设多少钱 成都网站设计 成都网站建设公司 成都网站制作