SQL Server 通过with as方法查询树型结构
数据库  /  管理员 发布于 5年前   401
一、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)
好了这篇文章就介绍到这了,希望能帮助到你。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号