您可以通过递归cte执行此操作:
DECLARE @t TABLE ( Name VARCHAr(100) , CategoryId INT , ParentCategoryId INT )INSERT INTO @tVALUES ( '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



