小编典典

如何在MSSQL 2005中创建递归查询?

sql

假设我有下表:

CustomerID ParentID Name
========== ======== ====
1          null     John
2          1        James
3          2        Jenna
4          3        Jennifer
5          3        Peter
6          5        Alice
7          5        Steve
8          1        Larry

我想在一个查询中检索詹姆斯的所有后代(詹娜,詹妮弗,彼得,爱丽丝,史蒂夫)。谢谢,巴勃罗。


阅读 173

收藏
2021-04-15

共1个答案

小编典典

在SQL Server2005上,您可以使用CTE(公用表表达式)

with Hierachy(CustomerID, ParentID, Name, Level)
as
(
select CustomerID, ParentID, Name, 0 as Level
    from Customers c
    where c.CustomerID = 2 -- insert parameter here
    union all
    select c.CustomerID, c.ParentID, c.Name, ch.Level + 1
    from Customers c
    inner join Hierachy ch
    on c.ParentId = ch.CustomerID
)
select CustomerID, ParentID, Name
from Hierachy
where Level > 0
2021-04-15