如何使用SQL Server的HierarchyID查找所有子体
我需要使用如何使用SQL Server的HierarchyID查找所有子体,sql,sql-server-2008,tsql,hierarchyid,Sql,Sql Server 2008,Tsql,Hierarchyid,我需要使用SQL Server的HierarchyID查找类别的所有后代 我知道如何找到直接的孩子,但我想找到孩子的孩子的孩子等等 有没有一种方法可以使用HierarchyID?如果你有你想要的树的根,你就不能使用: DECLARE @root hierarchyID; SELECT @root = col FROM yourTable WHERE [whatever uniquely identifies this row] SELECT * FROM yourTable WHERE co
SQL Server
的HierarchyID
查找类别的所有后代
我知道如何找到直接的孩子,但我想找到孩子的孩子的孩子等等
有没有一种方法可以使用
HierarchyID
?如果你有你想要的树的根,你就不能使用:
DECLARE @root hierarchyID;
SELECT @root = col
FROM yourTable
WHERE [whatever uniquely identifies this row]
SELECT *
FROM yourTable
WHERE col.IsDescendantOf(@root) = 1
在我的示例中,我假设您的表如下所示:
DECLARE TABLE MyTable
(
HID hierarchyid PRIMARY KEY,
ID int IDENTITY(1, 1),
SomeText varchar(50)
);
如果要将ID为3的节点的所有Decentant降低到最大级别(从根节点开始)5:
DECLARE@searchNode hierarchyid;
选择@searchNode=HID
从MyTable
其中ID=3;
挑选*
从MyTable
其中HID.isdescendatof(@searchNode)
和HID.GetLevel()对于这类查询,我非常喜欢使用CTE,因为根据代码的结构,您可以灵活地选择只返回子级还是父级,或者两者都返回。在本例中,我返回两者的并集,举个例子
declare @MyTable table
(
ID int not null,
HierId hierarchyid null
);
declare @id int
set @id = 1
;with parent (TenantId, HierId, IsParent) as
(
select
t.ID
,t.HierId
,cast(1 as bit) as IsParent
from @MyTable t
where t.ID = @id
), children as
(
select
t.ID
,t.HierId
,cast(0 as bit) as IsParent
from
@MyTable t
inner join parent p
on t.HierId.IsDescendantOf(p.HierId) = 1
)
select
*
from parent
UNION
select *
from children
Marc-如何将子体限制为X级深度?@IEnumerator-可以使用col.GetLevel()
并将其添加到where子句中
WHERE HID.IsDescendantOf(@searchNode) = 1
AND HID.GetLevel() <= (@searchLevel + 2);
declare @MyTable table
(
ID int not null,
HierId hierarchyid null
);
declare @id int
set @id = 1
;with parent (TenantId, HierId, IsParent) as
(
select
t.ID
,t.HierId
,cast(1 as bit) as IsParent
from @MyTable t
where t.ID = @id
), children as
(
select
t.ID
,t.HierId
,cast(0 as bit) as IsParent
from
@MyTable t
inner join parent p
on t.HierId.IsDescendantOf(p.HierId) = 1
)
select
*
from parent
UNION
select *
from children