0

我正在创建一个同时具有自引用外键和层次结构的表。

有没有比为每个节点创建它更简单的方法来填充hierarchyid,如下所示?

DECLARE @ID INT = 9

UPDATE  dbo.Tree
SET     Path = ( SELECT Path
             FROM   dbo.Tree
             WHERE  ID = 3).GetDescendant(( SELECT  PATH
                                            FROM    dbo.Tree
                                            WHERE   ID = @ID - 1
                                          ), NULL)
WHERE   ID = @ID

在此示例中,父节点的 ID 为 3,并且 8 和 9 是 3 的子节点。

4

1 回答 1

0

我现在能找到的最佳解决方案是将根节点设置在哪里ParentID = -1,然后执行以下脚本。

DECLARE c1 CURSOR FOR (SELECT ID, ParentID FROM dbo.Tree WHERE ParentID != -1)

UPDATE dbo.Tree SET Path = NULL WHERE ParentID != -1

OPEN c1

DECLARE @ID INT, @ParentID INT

FETCH NEXT FROM c1 INTO @ID, @ParentID

WHILE @@FETCH_STATUS = 0
BEGIN

    UPDATE dbo.Tree SET Path = (SELECT Path FROM dbo.Tree WHERE ID = @ParentID).GetDescendant(
    (SELECT MAX(PATH) FROM dbo.Tree WHERE ParentID = @ParentID), NULL) WHERE ID = @ID

    FETCH NEXT FROM c1 INTO @ID, @ParentID
END

CLOSE c1
DEALLOCATE c1
于 2014-11-25T11:55:59.177 回答