Sql Hierarchy loop query

后端 未结 1 1456
再見小時候
再見小時候 2021-01-25 00:42

This table represents a category hierarchy and the element at top of the hierarchy has the parent id as NULL. The table is as the exaple below:

**categoryId cate         


        
相关标签:
1条回答
  • you can use recursive cte:

    with cte as (
       select
          t.categoryId, t.categoryName, t.parentId,
          cast(t.categoryId as nvarchar(max)) as path
       from categories as t
       where t.categoryId = 234
    
       union all
    
       select
          c.categoryId, c.categoryName, t.parentId,
          c.path + '->' + cast(t.categoryId as nvarchar(max))
       from categories as t
           inner join cte as c on c.parentId = t.categoryId
    )
    select categoryid, categoryname, path + '->NULL'
    from cte
    where parentid is null
    

    sql fiddle demo

    0 讨论(0)
提交回复
热议问题