SQL Server 通过with as方法查询树型结构
2019-11-07 18:12
2046 查看
一、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 树型结构查询指定节点 SQL Server 树型结构查询的排序
- 使用SQL SERVER 2005/2008 递归CTE查询树型结构
- 使用SQLSERVER 2005/2008 递归CTE查询树型结构的方法
- 通过SQL Server的位运算功能巧妙解决多选查询方法
- Java 通过JDBC查询数据库表结构(字段名称,类型,长度等)
- SQL Server阻止保存修改表结构的解决方法
- 查询MySQL数据库中表结构的几种方法
- 通过API文档查询Math的方法打印近似圆
- SQL Server查询速度慢的原因及优化方法
- [Elasticsearch] 控制相关度 (三) - 通过查询结构调整相关度以及boosting查询
- 在 SQL Server 2005 中查询表结构及索引
- SQL Server 2005查询处理结构-用户模式计划(UMS)
- SQL server学习(二)表结构操作、SQL函数、高级查询
- mysql中复制表结构的方法(亲测通过)
- sql server 中 bit 字段的 查询方法
- 通过java查询数据库表结构
- 【greenplum】greenplum 数据字典实践--通过sql脚本查询表结构,拼装建表语句
- 通过SQL Server命令行启动及停止SQL服务的方法
- 使用postgre数据库实现树形结构表的子-父级迭代查询,通过级联菜单简单举例
- SQL Server 2008查询IP地址方法