0

Could you, please, help me to checkthat a node with hierarchyid '/1/1/' has (or has not) a child node with hierarchyid '/1/1/X'?

2 Answers2

0

This returns all the children of a specified item, just as you like:

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
sergiogarciadev
  • 2,061
  • 1
  • 21
  • 35
0

You can check for this by seeing if the hierarchyid has any children on the level immediately below it.

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
JamieSee
  • 12,696
  • 2
  • 31
  • 47