在 SQL 2008 上使用层次结构数据类型。层次结构中的节点如下所示:
value node
36 /8/1/
38 /8/2/
34 /8/3/
40 /8/4/
42 /8/5/
44 /8/6/
46 /8/7/
48 /8/8/
我想重新排列节点,以便/8/3/和/8/1/交换位置。知道如何做到这一点吗?
到目前为止,我唯一的想法是加载数组中某个级别上的所有节点,按照我想要的方式对它们进行排序,从表中删除它们并以排序的形式插入。
最佳答案
如果(如您的示例中)您提前知道要操作的 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;
请注意,在此示例中,hierarchyid 并不保持相同。至少有一个最终会使用“分数”来表示其位置(例如“/8/2.5/”而不是“/8/3/”)。
关于sql - 对 SQL 层次结构数据类型中的节点重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1283877/