如何检查具有hierarchyid'/ 1/1 /'的节点是否具有hierarchyid'/ 1/1 / x'的子节点?

时间:2013-11-29 19:13:50

标签: hierarchyid

请帮助我检查一个带有hierarchyid' / 1/1 /'的节点。有(或没有)带有hierarchyid' / 1/1 / X'的儿童节点?

2 个答案:

答案 0 :(得分:0)

这将返回指定项目的所有子项,如您所愿:

DECLARE @DemoTable AS TABLE
(
    Id              int identity(1, 1) primary key,
    Hierarchy       hierarchyid,
    Name            varchar(100)
)

INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/', 'Universe')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/1/', 'Milky Way')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/2/', 'Andromeda')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/1/1/', 'Solar System')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/1/1/1/', 'Mercury')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/1/1/2/', 'Venus')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/1/1/3/', 'Earth')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/1/1/3/1/', 'Moon')
INSERT INTO @DemoTable (Hierarchy, Name) VALUES ('/1/1/4/', 'Mars')

--
-- All children Solar System
--
SELECT 
    T.Hierarchy.GetLevel() as Level, 
    T.Hierarchy.ToString() as Hierarchy, 
    T.Name
FROM @DemoTable T
JOIN @DemoTable P ON
    T.Hierarchy.GetAncestor(1) = P.Hierarchy
WHERE P.Name = 'Solar System'
ORDER BY
    T.Hierarchy

答案 1 :(得分:0)

您可以通过查看hierarchyid是否在其下方的级别上有任何子级来检查这一点。

DECLARE @hierarchyID hierarchyid

SET @hierarchyID = '/1/1/'

SELECT CASE 
        WHEN EXISTS (
                SELECT 1
                FROM HierarchyTable
                WHERE HierarchyIDColumn.IsDescendantOf(@hierarchyID) = 1
                    AND HierarchyIDColumn.GetLevel() = @hierarchyID.GetLevel() + 1
                )
            THEN 1
        ELSE 0
        END AS HasImmediateChildren