我在表格中使用了hierarchyid(SQL Server 2008 R2)。我必须找到多个节点的所有后代。我父母的结果如下:
| Parent |
|:-----------|
| 0x6CB0AC |
| 0x6CB180 |
| 0x6CB181 |
| 0x6CB141 |
| |
我应该如何编写将返回每个父母的所有后代的查询?
我的桌子设计:
ID: HierarchyId
Name: varchar(100)
Surname: varchar(100)
答案 0 :(得分:2)
假设表名是Tree,这里有查询:
;WITH P AS
(
SELECT CAST(ParentId AS hierarchyid) AS ParentId
FROM
(VALUES (0x6CB0AC), (0x6CB180))
AS Parents(ParentId)
)
SELECT *
FROM
Tree T
WHERE
EXISTS (
SELECT *
FROM P
WHERE T.Id.IsDescendantOf(P.ParentId) = 1
)
编辑:我删除了最后两个二进制字符串,因为它们不是有效的hierarchyid的
编辑:这里有一个示例,显示1.1和1.2的后代,层次结构为0x5AC0和0x6AC0。
CREATE TABLE Tree
(
Id hierarchyid PRIMARY KEY,
Name varchar(100)
);
INSERT INTO Tree(Id, Name) VALUES
('/1/', '1'),
('/1/1/', '1.1'),
('/1/1/1/', '1.1.1'),
('/1/1/2/', '1.1.2'),
('/2/', '2'),
('/2/1/', '2.1'),
('/2/1/1/', '2.1.1'),
('/2/1/2/', '2.1.2');
WITH Ids AS
(
SELECT CAST(Id as hierarchyid) AS Id
FROM (VALUES (0x5AC0), (0x6AC0)) T(Id)
)
SELECT T.*
FROM
Tree T
WHERE
EXISTS (
SELECT *
FROM Ids
WHERE T.Id.IsDescendantOf(Ids.Id) = 1
)
结果:
+--------+-------+
| Id | Name |
+--------+-------+
| 0x5AC0 | 1.1 |
| 0x5AD6 | 1.1.1 |
| 0x5ADA | 1.1.2 |
| 0x6AC0 | 2.1 |
| 0x6AD6 | 2.1.1 |
| 0x6ADA | 2.1.2 |
+--------+-------+
请注意,IsDescendantOf将Parent视为自己的后代。
答案 1 :(得分:0)
Select parent.ID, child.*
From dbo.YourTable as child
Join dbo.YourTable as parent
On child.HierarchyColumn.IsDescendantOf(parent.HierarchyColumn) = 1