我有一组数据,如下所示:
ID, Description, ParentID
1, Savoury, -1
2, Cheese, 1
3, Pastry, 1
4, Quiche, 1
5, Sweet, -1
6, Chocolate, 5
...
我要做的是编写一个存储过程,它将产生一组类似于 Web 浏览器中的面包屑链接的结果。像下面这样的东西是理想的......
ID, BreadCrumb
1, Savoury
2, Savoury >> Cheese
3, Savoury >> Pastry
4, Savoury >> Quiche
5, Sweet
6, Sweet >> Chocolate
...
奶酪或糕点等物品不会单独列为物品(如 Sweet 是)。到目前为止,我有以下代码有效,但它列出了所有内容,无论它是否有 ParentID
With BreadCrumb AS
(
SELECT CAST(a.Description AS VARCHAR(100)) AS Path, a.ID, a.ParentID
FROM FoodStuff a
UNION ALL
SELECT CAST(BreadCrumb.Path + ' >> ' + b.Description AS VARCHAR(100)) AS Path, b.ID, b.ParentID
FROM FoodStuff b
INNER JOIN BreadCrumb ON BreadCrumb.ID = b.ParentID
)
SELECT * FROM BreadCrumb
ORDER BY Path
我会很感激朝着正确的方向轻推。
在此先感谢,凯夫