如果(如在您的示例中)您知道要提前操作的 hierarchyid 值,则可以直接进行,例如:
-- Place 1st node between 2nd and 3rd
UPDATE yourTable SET node = CAST('/8/2.5/' AS hierarchyid) WHERE value = 36;
-- Move 3rd node to 1st
UPDATE yourTable SET node = CAST('/8/1/' AS hierarchyid) WHERE value = 34;
如果您需要动态获取新的 hierarchyid 值,请查看GetDescendant()和GetAncestor()函数。使用它,该示例将如下所示:
DECLARE @Parent hierarchyid, @Child1 hierarchyid, @Child2 hierarchyid
-- Grab hierarchyids from 2nd and 3rd node
SELECT @Child1 = node FROM yourTable WHERE value = 38;
SELECT @Child2 = node FROM yourTable WHERE value = 34;
-- Get the parent hierarchyid
SELECT @Parent = @Child1.GetAncestor(1);
-- Update 1st node to end up between 2nd and 3rd
UPDATE yourTable SET node = @Parent.GetDescendant(@Child1, @Child2) WHERE value = 36;
-- Update 3rd node to end up before 2nd
UPDATE yourTable SET node = @Parent.GetDescendant(NULL, @Child1) WHERE value = 34;
请注意,在此示例中,hierarchyids 不会保持不变。至少有一个最终会使用“分数”作为其位置(例如“/8/2.5/”而不是“/8/3/”)。