SQLSERVER 2005 递归查询
来源:互联网 发布:监控ip修改软件 编辑:程序博客网 时间:2024/05/19 00:10
项目中有用户组表UserGroup如下:
其中PID表示当前组的上级组
表数据如下:
现在想查询出顶级组[没有上级组叫顶级组]A1组的所有子孙组ID,SQL如下:
- --查询子节点
- with
- RTD1 as(
- select id ,pid from UserGroup
- ),
- RTD2 as(
- select * from RTD1where id=6
- union all
- select RTD1.* from RTD2 innerjoin RTD1
- on RTD2.id=RTD1.PID
- )
- select * from RTD2
--查询子节点with RTD1 as(select id ,pid from UserGroup),RTD2 as(select * from RTD1 where id=6union allselect RTD1.* from RTD2 inner join RTD1 on RTD2.id=RTD1.PID)select * from RTD2
查询结果如下:
id pid
----------- -----------
6 NULL
17 6
18 6
20 6
21 20
22 20
23 20
24 20
29 20
25 23
26 23
28 26
27 25
(13 行受影响)
现在想查询出A1-B3-C3-D2组的所有上级组ID,SQL如下:
- --查询父节点
- with
- RTU1 as(
- select id ,pid from UserGroup
- ),
- RTU2 as(
- select * from RTU1where id=26
- union all
- select RTU1.* from RTU2 innerjoin RTU1
- --on myT2.id=myT.PID
- on RTU2.PID=RTU1.ID
- )
- select * from RTU2
--查询父节点with RTU1 as(select id ,pid from UserGroup),RTU2 as(select * from RTU1 where id=26union allselect RTU1.* from RTU2 inner join RTU1 --on myT2.id=myT.PIDon RTU2.PID=RTU1.ID)select * from RTU2
查询结果如下:
id pid
----------- -----------
26 23
23 20
20 6
6 NULL
(4 行受影响)
- SQLSERVER 2005 递归查询
- SQLSERVER 2005 递归查询
- SqlServer递归查询
- sqlserver 递归查询
- sqlserver 递归查询
- sqlserver递归查询
- SqlServer递归查询
- SQLServer 递归查询
- SQLServer 递归查询
- SQLserver递归查询
- sqlserver递归查询
- SQLServer 递归查询
- sqlserver递归查询
- SqlServer递归查询
- SQLServer递归查询
- sqlserver 递归查询
- SQLSERVER 递归查询
- SQL递归查询 SqlServer/ORACLE递归查询
- hdu 1227 fast food
- 次小生成树 附 poj1679The Unique MST
- 思维导图 mindmanager 错误 DynaZip UnZIP Error:Error creating output file 解决
- linux基础编程:进程通信之套接字
- 读取pdf文件内容
- SQLSERVER 2005 递归查询
- tiny6410_按键中断驱动_异步通知
- jsp
- Linux压力测试与LTP体系结构
- 11-14游标
- 梯度下降法
- 再学C++ Primer(9)-类
- Android tabhost下面的listview点击事件为什么不行
- process monitor工具下载地址