Sql Hierarchy循环查询

时间:2013-08-25 08:38:18

标签: sql sql-server

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

1 个答案:

答案 0 :(得分:3)

你可以使用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

相关问题