SQL树叶节点更新

时间:2018-06-28 13:37:39

标签: sql azure-sql-database

我正在尝试更新类似于树的表。我想更新一列以确定每个节点是否为叶节点。 该表如下所示:

#NodeTable:
NodeID | ParentID | IsLeaf
--------------------------
0      | NULL     | 0 
1      | 0        | 0
3      | 1        | 0
5      | 3        | 0
6      | 3        | 0
7      | 1        | 0

我正在尝试使用以下命令更新表:

UPDATE #NodeTable
SET IsLeaf = 
    CASE
        WHEN NodeID IN (SELECT ParentID FROM #NodeTable) THEN 0 ELSE 1
    END

逻辑是,如果NodeID出现在(SELECT ParentID ..)中,则它不是叶节点,因此IsLeaf应该为0;否则,如果IsLeaf不存在,则为叶子,IsLeaf应该为1。

但是,此声明未达到我的预期。任何帮助将不胜感激。

最终结果应如下所示:

NodeTable:

NodeID | ParentID | IsLeaf
--------------------------
0      | NULL     | 0 
1      | 0        | 0
3      | 1        | 0
5      | 3        | 1
6      | 3        | 1
7      | 1        | 1

2 个答案:

答案 0 :(得分:2)

如果只需要标记叶子,则可以对所有父母使用NOT EXISTS

IF OBJECT_ID('tempdb..#NodeTable') IS NOT NULL
    DROP TABLE #NodeTable

CREATE TABLE #NodeTable (
    NodeID INT,
    ParentID INT,
    IsLeaf BIT DEFAULT 0)

INSERT INTO #NodeTable (
    NodeID,
    ParentID)
VALUES
    (0, NULL),
    (1, 0),
    (3, 1),
    (5, 3),
    (6, 3),
    (7, 1)

UPDATE L SET
    IsLeaf = 1
FROM
    #NodeTable AS L
WHERE
    NOT EXISTS (SELECT 'does not have any children' FROM #NodeTable AS P WHERE L.NodeID = P.ParentID)


SELECT * FROM #NodeTable AS T ORDER BY T.NodeID

答案 1 :(得分:1)

您可以使用EXISTS

UPDATE n 
     SET n.IsLeaf = (CASE WHEN EXISTS (SELECT 1 FROM #NodeTable WHERE ParentID = n.NodeID) THEN 0 ELSE 1 END)
FROM #NodeTable n;