How do I create a recursive query in MSSQL 2005?

后端 未结 4 452
心在旅途
心在旅途 2021-01-30 14:31

Let\'s say I have the following table:

CustomerID ParentID Name
========== ======== ====
1          null     John
2          1        James
3          2        J         


        
4条回答
  •  醉梦人生
    2021-01-30 15:00

    On SQL Server 2005 you can use 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
    

提交回复
热议问题