SQL Server CTE -Find top parentID forEach childID?

后端 未结 9 1081
Happy的楠姐
Happy的楠姐 2020-12-08 08:24

I have a table which contains hierarchy data - something like:

childID  |  parentID
____________________
  1      |     5
  5      |     9
  9      |     20         


        
9条回答
  •  爱一瞬间的悲伤
    2020-12-08 08:51

    Consider this sample data and respective SQL to access child records along with their top parent.

    Sample DATA

    SQL code:

    ;WITH c AS (
       SELECT Id, Name, ParentId as CategoryId, 
              Id as MainCategoryId, Name AS MainCategory 
         FROM   pmsItemCategory 
         WHERE  ParentId is null
    
         UNION ALL 
    
         SELECT T.Id, T.Name, T.ParentId,  MainCategoryId, MainCategory 
         FROM   pmsItemCategory AS T 
                INNER JOIN c  ON T.ParentId = c.Id 
         WHERE  T.ParentId is not null
        ) 
    
    SELECT Id, Name, CategoryId, MainCategoryId, MainCategory 
    FROM   c 
    order by Id
    

提交回复
热议问题