假设我有下表:

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

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

最佳答案

在SQL Server 2005上,您可以使用CTEs (Common Table Expressions):

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

关于sql - 如何在MSSQL 2005中创建递归查询?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/239275/

10-12 14:13