日期:2014-05-16  浏览次数:20593 次

SQL Server 查询树结构的表,查询一个节点的所有子节点
数据库设计如下

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之下的所有节点
------解决方案--------------------
;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

------解决方案--------------------


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

------解决方案--------------------
可以参考这个:

在论坛中出现的比较难的sql问题:21(递归问题3)
http://blog.csdn.net/sqlserverdiscovery/article/details/18363633