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

后端 未结 3 912
不思量自难忘°
不思量自难忘° 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:47

    Here is my solution, Sql Fiddle

    DECLARE @child VARCHAR(10) = 'C'
    
        ;WITH children AS
        (
    
           SELECT 
             ParentCategoryId,
            CAST(ISNULL(ParentCategoryId + '->' ,'')  + ChildCategoryId AS VARCHAR(4000)) AS Path
           FROM Hierarchy
           WHERE ChildCategoryId =  @child
         UNION ALL
           SELECT 
             t.ParentCategoryId,
             list= CAST(ISNULL(t.ParentCategoryId  + '->' ,'')  + d.Path AS VARCHAR(4000))
           FROM Hierarchy t
           INNER JOIN children  AS d
                ON t.ChildCategoryId = d.ParentCategoryId
         )
    
        SELECT Path 
        from children c
        WHERE ParentCategoryId IS NULL
    

    Output:

    A->D->C 
    A->B->C 
    

    UPDATE:

    @AlexeiMalashkevich, to just get id, you may try this

    SQL Fiddle

    DECLARE @child VARCHAR(10) = 'C'
    
    ;WITH children AS
    (
    
       SELECT 
         ParentCategoryId,
         ChildCategoryId  AS Path
       FROM Hierarchy
       WHERE ChildCategoryId =  @child
     UNION ALL
       SELECT 
         t.ParentCategoryId,
         d.ParentCategoryId 
       FROM Hierarchy t
       INNER JOIN children  AS d
            ON t.ChildCategoryId = d.ParentCategoryId
     )
    
    SELECT DISTINCT PATH
    from children c
    

提交回复
热议问题