Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
对SQL层次结构数据类型中的节点重新排序_Sql_Tsql_Hierarchy_Common Table Expression - Fatal编程技术网

对SQL层次结构数据类型中的节点重新排序

对SQL层次结构数据类型中的节点重新排序,sql,tsql,hierarchy,common-table-expression,Sql,Tsql,Hierarchy,Common Table Expression,在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/ DECLARE @Parent hierarchyid, @Child1 hierarchyid, @Child2 hierarchyid -- Grab hierarchyids from 2nd a

在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/
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;
我想重新排列节点,以便/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值,请查看和函数。使用该选项,示例将如下所示:

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/
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;

请注意,在本例中,层次结构并不保持不变。至少有一个最终会使用“分数”作为其位置(例如,/8/2.5/”而不是“/8/3/”)。

不要因为你糟糕的例子而惩罚别人。根据您提供的数据,按值排序是有效的;你需要纠正或解释为什么不是这样。我的问题是-重新排列层次结构中的节点。按值排序是否会重新排序节点?我不知道可以这样更新层次ID。这就是我问题的答案。我现在无法撤销我被接受的答案,但我会接受你的。谢谢