【问题标题】:how can I check that a node with hierarchyid '/1/1/' has a child node with hierarchyid '/1/1/x'?如何检查具有hierarchyid '/1/1/' 的节点是否有一个具有hierarchyid '/1/1/x' 的子节点?
【发布时间】:2013-11-29 19:13:50
【问题描述】:

能否请您帮我检查一个带有 hierarchyid '/1/1/' 的节点是否有(或没有)一个带有 hierarchyid '/1/1/X' 的子节点?

【问题讨论】:

    标签: hierarchyid


    【解决方案1】:

    这将返回指定项的所有子项,就像您喜欢的那样:

    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
    

    【讨论】:

      【解决方案2】:

      您可以通过查看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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-22
        • 2017-03-26
        • 2017-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多