SQL Server 查询树结构的表,查询一个节点的所有子节点

NotNull 2014-03-26 11:13:12
数据库设计如下

Create Table Tab
(
Id int ,
PId int
)
INSERT INTO dbo.Tab
( Id, PId )
SELECT 1,NULL
UNION
SELECT 2,NULL
UNION
SELECT 3,1
UNION
SELECT 4,1
UNION
SELECT 5,1
UNION
SELECT 6,3
UNION
SELECT 7,2

SELECT * FROM dbo.Tab


下面的数据不固定,不一定有多少个子节点
求助,如何查询节点1之下的所有节点
...全文
1645 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
LongRui888 2014-03-26
  • 打赏
  • 举报
回复
可以参考这个: 在论坛中出现的比较难的sql问题:21(递归问题3) http://blog.csdn.net/sqlserverdiscovery/article/details/18363633
sedshy 2014-03-26
  • 打赏
  • 举报
回复


with ct (ChildID, ParentID, [Level]) as (
	select ChildID, ParentID, 1 as [Level] from LinkTable where ParentID = 284
	union all
	select  e.ChildID, e.ParentID, [Level] + 1 from ct t, LinkTable e
	where t.ChildID = e.ParentID
)
select * from ct
直面人生 2014-03-26
  • 打赏
  • 举报
回复
引用 4 楼 xxfvba 的回复:
哈哈,写的都一样啊
是阿,懒得写了 直接引用
xxfvba 2014-03-26
  • 打赏
  • 举报
回复
哈哈,写的都一样啊
xxfvba 2014-03-26
  • 打赏
  • 举报
回复
with cte as (select id,pid from Tab where pid=1 union all select t.id,a.pid from cte a,Tab t where t.pid=a.id) select * from cte
直面人生 2014-03-26
  • 打赏
  • 举报
回复
引用 1 楼 fredrickhu 的回复:
;with f as 
(
select * from tab where id=1
union all
select a.* from tab as a inner join f as b on a.pid=b.id
)

select * from f
向版主这样用CTE递归就搞定了
--小F-- 2014-03-26
  • 打赏
  • 举报
回复
;with f as 
(
select * from tab where id=1
union all
select a.* from tab as a inner join f as b on a.pid=b.id
)

select * from f

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧