0
NodeId NodeName ParentId 权限
-----------------------------------------------------------
1 节点 1 0 1
2 节点 2 1 空
3 节点 3 1 空
4 节点 4 1 空
5 节点 5 2 空
6 节点 6 5 空
7 节点 7 2 空

我在 Node6 中,我需要在树中获得第一个非 NULL 权限 (6->5->2->1-> Permission = 1) 我该怎么做?

4

1 回答 1

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');
于 2013-05-27T10:52:58.753 回答