【问题标题】:How to get the child nodes from a parent node from a table in SQL?如何从 SQL 表中的父节点获取子节点?
【发布时间】:2015-03-19 23:34:26
【问题描述】:

假设我的数据库中有以下分层表示:

A
|_B_C
|_D

然后我想从 A(或 B)获取子节点。 反之亦然,我想从给定的子节点获取父节点?

CREATE TABLE tbl (
   Node HierarchyID PRIMARY KEY CLUSTERED,
   NodeLevel AS Node.GetLevel(),
   ID INT UNIQUE NOT NULL,
   Name VARCHAR(50) NOT NULL
 ) 

插入根:

INSERT INTO tbl (Node, ID, Name)
   VALUES (HierarchyId::GetRoot(), 1, 'A') 

孩子B

DECLARE @parent HierarchyId = HierarchyId::GetRoot()
INSERT INTO tbl (Node,ID,Name) VALUES (@parent.GetDescendant(NULL,NULL),2,'B')

【问题讨论】:

  • 表格定义、示例数据和所需结果会有所帮助。

标签: sql tsql hierarchyid


【解决方案1】:
select @child = node from tbl where id = 2;
-- get immediate ancestor
select * from dbo.tbl where Node = @child.GetAncestor(1);

-- get immediate children
select
    *
from
    dbo.tbl
where
    Node.IsDescendantOf(@parent) = 1 and 
    Node.GetLevel() = @parent.GetLevel() + 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多