我正在创建一个包含自引用外键和hierarchyid的表。
是否有一种更简单的方法来填充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的子节点。
答案 0 :(得分: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