0

データベースに次の階層表現があるとします。

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')
4

1 に答える 1

0
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;
于 2015-03-20T00:43:39.563 に答える