How can I generate a hierarchy path in SQL that leads to a given node?

后端 未结 3 908
不思量自难忘°
不思量自难忘° 2020-12-07 03:24

In my MS SQL 2008 R2 database I have this table:

TABLE [Hierarchy]
[ParentCategoryId] [uniqueidentifier] NULL,
[ChildCategoryId] [uniqueidentifier] NOT NULL         


        
3条回答
  •  温柔的废话
    2020-12-07 03:57

    That's an interesting hierarchy structure. Seems to allow for parents to possibly be children of their children. If this were to happen this code logic would break, but as long as that doesn't occur this should work.

    Create  Function dbo.IdentifyHierarchyPaths (@DeepestChildNode UniqueIdentifier)
    Returns @hierarchy Table
    (
            Hierarchy Varchar(Max)
    )
    As
    Begin
            ;With   BuildHier As
            (
                    Select  Convert(Varchar(Max),h2.ChildCategoryId) As child, Convert(Varchar(Max),h1.ChildCategoryId) + ' > ' +  Convert(Varchar(Max),h2.ChildCategoryId) As hier
                    From    Hierarchy h1
                    Left    Join Hierarchy h2
                            On  h1.ChildCategoryId = h2.ParentCategoryId
                    Where   h1.ParentCategoryId Is Null
                    Union   All
                    Select  Convert(Varchar(Max),h1.ChildCategoryId) As child, bh.hier + ' > ' +  Convert(Varchar(Max),h1.ChildCategoryId) As hier
                    From    BuildHier bh
                    Join    Hierarchy h1
                            On  bh.child = h1.ParentCategoryId
            ),      HierWithTopLevel As
            (
                    Select  Convert(Varchar(Max),ChildCategoryId) As hierarchy
                    From    Hierarchy
                    Where   ParentCategoryId Is Null
                    Union   
                    Select  hier
                    From    BuildHier
            )
            Insert  @hierarchy
            Select  hierarchy
            From    HierWithTopLevel
            Where   Right(hierarchy,36) = Convert(Varchar(36),@DeepestChildNode);
            Return;
    End;
    

提交回复
热议问题