SQL Server如何通过with as方法查询树型结构
发表于:2024-09-26 作者:千家信息网编辑
千家信息网最后更新 2024年09月26日,SQL Server如何通过with as方法查询树型结构,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。一、with as 公用表表
千家信息网最后更新 2024年09月26日SQL Server如何通过with as方法查询树型结构
SQL Server如何通过with as方法查询树型结构,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
一、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方法查询树型结构问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。
递归
表达式
方法
结构
查询
条件
节点
问题
公用
最大
对象
层级
更多
语句
帮助
解答
易行
简洁
差不多
简单易行
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
华为还有敏捷软件开发
服务器怎么连接电脑上网
上海移人网络技术有限公司
怎么测试服务器的防护
代理服务器访问不了https
行业加强网络安全管理
数据库不能自动清理备份文件
青少年网络安全教育工
dz数据库帖子数据表
各厂商服务器额定功率
学校建立网站需要服务器吗
宇视科技服务器代工
dnf服务器怎么改善
web服务器如何配置站点
用友软件服务器地址
企业网络安全解决方案的思路
网络软件开发包括
苏州橙仓网络技术有限公司
王牌竞速官服服务器
网络安全宣传对联
警惕网络安全文章
《网络安全法》的立法方针是
大恒相机实时监测软件开发
同花顺服务器在哪儿
软件开发的语言有哪几种
从事网络技术的前景
有名的棋牌软件开发
数据库的批量保存
二年级手抄报网络安全简单
网络安全形态意识