2

在 SQL 2008 上使用 Hierarchy 数据类型。我的层次结构中的节点如下所示:

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/ 切换位置。关于如何做到这一点的任何想法?

到目前为止,我唯一的想法是我将所有节点加载到 Array 中的一个级别,按照我想要的方式对它们进行排序,从表中删除它们并以排序形式插入。

4

2 回答 2

4

如果(如在您的示例中)您知道要提前操作的 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/”)。

于 2009-08-30T10:41:35.377 回答
0

找到了解决方案

http://technet.microsoft.com/en-us/library/bb677256.aspx

于 2009-08-30T10:39:40.093 回答