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

标签 sql t-sql 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/

我想重新排列节点,以便/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/

相关文章:

c# - 检索类型的叶接口(interface)

java - 如何在 Eclipse 中找到抽象方法的实现位置?

sql - 使用 CONNECT BY 通过 Oracle 中的 SQL 查询获取 Hierarchy 中的所有父级和一个子级

java - 非常快地将多行插入 Oracle 数据库

mysql - 从表中按顺序显示记录而不依赖于表的 id?

SQL Azure 不支持 'select into' - 还有其他方法吗?

t-sql - 在子查询中使用 MAX() 时为 "SQL Server Subquery returned more than 1 value"

sql - LibreOffice calc 到 PGAdmin 3?

mysql - 按年份连接 SQL 结果(年份、品牌、型号)

sql - 查询每组中的前 2 个