1

此表表示类别层次结构,层次结构顶部的元素的父 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)

4

1 回答 1

3

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

于 2013-08-25T08:46:51.533 回答