admin

如何以逗号分隔的CategoryIds递归获取?

sql

我有一个这样的表:

Name           CategoryId    ParentCategoryId
Footwear       93            0
Men Shoes      6             93
Female Shoes   7             93
Mobile         2             0
Smartphone     4             2

我需要像这样的输出:

Name            Categories 
Footwear        93,0    
Men Shoes       6,93,0    
Female Shoes    7,93,0    
Mobile          2,0   
Smartphone      4,2,0

基本上,我需要递归地获取类别ID,并将其设置为逗号分隔的字符串。我现在已经进入SQL3年了,我不知道如何获得这个结果。我尝试了其他SO问题的解决方案,但还是没有运气。


阅读 129

收藏
2021-06-07

共1个答案

admin

您可以通过递归cte执行此操作:

DECLARE @t TABLE
    (
      Name VARCHAR(100) ,
      CategoryId INT ,
      ParentCategoryId INT
    )
INSERT  INTO @t
VALUES  ( 'Footwear', 93, 0 ),
        ( 'Men Shoes', 6, 93 ),
        ( 'Female Shoes', 7, 93 ),
        ( 'Mobile', 2, 0 ),
        ( 'Smartphone', 4, 2 );

WITH    cte
          AS ( SELECT   * ,
                        CAST(CategoryId AS VARCHAR(100))  AS Categories
               FROM     @t
               WHERE    ParentCategoryId = 0
               UNION ALL
               SELECT   t.* ,
                        CAST(CAST(t.CategoryId AS VARCHAR(100)) + ','
                        + c.Categories AS VARCHAR(100))
               FROM     @t t
                        JOIN cte c ON c.CategoryId = t.ParentCategoryId
             )
    SELECT  *
    FROM    cte
2021-06-07