博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SQL SERVER 2005 递归查询备忘
阅读量:2235 次
发布时间:2019-05-09

本文共 1306 字,大约阅读时间需要 4 分钟。

--SQL SERVER 2005 递归查询use TestDBset nocount onif object_id('Dept','U') is not nulldrop table Deptgocreate table Dept(ID int,ParentID int,Name varchar(20))   insert into Dept select 1,0,'AA' insert into Dept select 2,1,'BB' insert into Dept select 3,1,'CC'  insert into Dept select 4,2,'DD'  insert into Dept select 5,3,'EE'  insert into Dept select 6,0,'FF' insert into Dept select 7,6,'GG' insert into Dept select 8,7,'HH' insert into Dept select 9,7,'II' insert into Dept select 10,7,'JJ' insert into Dept select 11,9,'KK'select * from Dept;--查询树状结构某节点的上级所有根节点。with cte_root(ID,ParentID,NAME)as(    --起始条件    select ID,ParentID,NAME    from Dept    where Name = 'II'   --列出子节点查询条件    union all    --递归条件    select a.ID,a.ParentID,a.NAME    from Dept a    inner join     cte_root b          --执行递归,这里就要理解下了     on a.ID=b.ParentID  --根据基础表条件查询子节点(a.ID),通过CTE递归找到其父节点(b.ParentID)。)                       --可以和下面查询子节点的cte_child对比。select * from cte_root ;--查询树状结构某节点下的所有子节点。with cte_child(ID,ParentID,NAME)as(    --起始条件    select ID,ParentID,NAME    from Dept    where Name = 'II' --列出父节点查询条件    union all    --递归条件    select a.ID,a.ParentID,a.NAME    from Dept a    inner join     cte_child b    on ( a.ParentID=b.ID)  --根据查询到的父节点(a.Parent),通过CTE递归查询出其子节点(b.ID))select * from cte_child --可以改变之前的查询条件'II'再测试结果

转载地址:http://bcsbb.baihongyu.com/

你可能感兴趣的文章
面试题 —— 关于main方法的十个面试题
查看>>
集成测试(一)—— 使用PHP页面请求Spring项目的Java接口数据
查看>>
使用Maven构建的简单的单模块SSM项目
查看>>
Intellij IDEA使用(十四)—— 在IDEA中创建包(package)的问题
查看>>
FastDFS集群架构配置搭建(转载)
查看>>
HTM+CSS实现立方体图片旋转展示效果
查看>>
FFmpeg 命令操作音视频
查看>>
问题:Opencv(3.1.0/3.4)找不到 /opencv2/gpu/gpu.hpp 问题
查看>>
目的:使用CUDA环境变量CUDA_VISIBLE_DEVICES来限定CUDA程序所能使用的GPU设备
查看>>
问题:Mysql中字段类型为text的值, java使用selectByExample查询为null
查看>>
程序员--学习之路--技巧
查看>>
解决问题之 MySQL慢查询日志设置
查看>>
contOS6 部署 lnmp、FTP、composer、ThinkPHP5、docker详细步骤
查看>>
TP5.1模板布局中遇到的坑,配置完不生效解决办法
查看>>
PHPstudy中遇到的坑No input file specified,以及传到linux环境下遇到的坑,模板文件不存在
查看>>
TP5.1事务操作和TP5事务回滚操作多表
查看>>
composer install或composer update 或 composer require phpoffice/phpexcel 失败解决办法
查看>>
TP5.1项目从windows的Apache服务迁移到linux的Nginx服务需要注意几点。
查看>>
win10安装软件 打开时报错 找不到 msvcp120.dll
查看>>
PHPunit+Xdebug代码覆盖率以及遇到的问题汇总
查看>>