小编典典

SQL层次结构循环查询

sql

该表表示类别层次结构,层次结构顶部的元素的父ID为NULL。该表如下所示:

**categoryId categoryName parentId**

1           Home         NULL
.           .            .
.           .            .
20          Vehicles      1
.           .           .
35          SUV          20
36          Motorbikes   20
.            .           .
90          BMW          35
91          Toyota       35
.            .           .
234         LandCruiser  91

Home>Vehicles>SUV>Toyota>LandCruiser

我正在尝试做的是建立一个SQL查询,这将使我返回:

任何给定[categoryId]的[categoryId],[categoryName]链。它应该循环并获取每一行,直到到达具有parentId ==
NULL的行为止。

如上面的示例示例234-> 91-> 35-> 20-> 1-> NULL(STOP)


阅读 244

收藏
2021-04-14

共1个答案

小编典典

您可以使用递归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

2021-04-14