在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值,就可以直接做,e.g:

-- 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 /').

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top