2013-05-27 106 views
0
 
NodeId NodeName ParentId Permission 
----------------------------------------------- 
1   Node1  0   1 
2   Node2  1   NULL 
3   Node3  1   NULL 
4   Node4  1   NULL 
5   Node5  2   NULL 
6   Node6  5   NULL 
7   Node7  2   NULL 

我在Node6和我需要獲得第一不是NULL允許在樹(6-> 5-> 2-> 1->權限= 1) 我該怎麼做?查詢爲父子關係到頂級

+0

你真的需要遞歸顯示多個分支。你使用的是哪個數據庫?您的層次結構是否有最大深度? –

+0

@gbn,SQL Server 2008 – Igor

+0

@MartinWilson,層次結構沒有最大深度。 – Igor

回答

1

由於Permission is NOT NULL必須位於層次結構中,因此此行成爲此情況的根節點。我已經標記這RootID這裏

還增加了更多的樣本數據來自同一ParentID = 0

DECLARE @t TABLE (NodeId int, NodeName varchar(100), ParentId int, Permission int) 
INSERT @t VALUES 
(1,'Node1',0,NULL), 
(2,'Node2',1,1), 
(3,'Node3',1,NULL), 
(4,'Node4',1,NULL), 
(5,'Node5',2,NULL), 
(6,'Node6',5,NULL), 
(7,'Node7',2,NULL), 
(8,'Node1',0,NULL), 
(9,'Node9',8,2), 
(10,'Node10',9,NULL), 
(11,'Node11',10,NULL), 
(12,'Node12',11,NULL), 
(13,'Node13',10,NULL), 
(14,'Node14',9,NULL); 

WITH CTE AS 
(
    SELECT NodeId, NodeName, ParentId AS RootID FROM @t WHERE Permission IS NOT NULL 
    UNION ALL 
    SELECT T.NodeId, T.NodeName, CTE.RootID 
    FROM @t T JOIN CTE ON T.ParentId = CTE.NodeId 
) 
SELECT 
    * 
FROM 
    CTE 
WHERE 
    NodeName IN ('Node6', 'Node13');