How to self JOIN recursively in SQL?

前端 未结 3 1692
长发绾君心
长发绾君心 2020-12-10 03:17

I have a table:

Series
========
ID
SeriesName
ParentSeriesID

A series can be a \"root\" series, (ParentSeriesID is 0 or null) or it can ha

相关标签:
3条回答
  • 2020-12-10 03:56

    Make use of CTE feature avaiable in slq server 2005 onwards for recurisve query

    USE AdventureWorks
    GO
    WITH Emp_CTE AS (
    SELECT EmployeeID, ContactID, LoginID, ManagerID, Title, BirthDate
    FROM HumanResources.Employee
    WHERE ManagerID IS NULL
    UNION ALL
    SELECT e.EmployeeID, e.ContactID, e.LoginID, e.ManagerID, e.Title, e.BirthDate
    FROM HumanResources.Employee e
    INNER JOIN Emp_CTE ecte ON ecte.EmployeeID = e.ManagerID
    )
    SELECT *
    FROM Emp_CTE
    GO
    

    You can view example over here :

    SQL SERVER – Simple Example of Recursive CTE

    0 讨论(0)
  • 2020-12-10 04:01

    I just enhance the work of Thomas. If you need to get the depth of the hierarchy and getting the parentid here is the code.

    This was almost the same with Thomas' work.

    With Family As 
    ( 
        Select s.ID, s.ParentSeriesId, 0 as Depth
        From Series s
        Where ID = @ParentID <--- this was removed if you intend to get all hierarchy of the record. You can retain this if you want
      Union All 
         Select s2.ID, s2.ParentSeriesId < --- change to **Family.ParentID**, Depth + 1
         From Series s2
         Join Family 
             On Family.ID = s2.ParentSeriesId 
    ) 
     Select *
     From Family 
    

    That's all. I know it's too late but I hope anyone who encounter this may help them. Thanks Thomas for the original code. :)

    0 讨论(0)
  • 2020-12-10 04:07

    If you are using SQL Server 2005+, you can use common-table expressions

    With Family As 
    ( 
    Select s.ID, s.ParentSeriesId, 0 as Depth
    From Series s
    Where ID = @ParentID 
    Union All 
    Select s2.ID, s2.ParentSeriesId, Depth + 1
    From Series s2
        Join Family 
            On Family.ID = s2.ParentSeriesId 
    ) 
    Select *
    From Family 
    

    For more:

    Recursive Queries Using Common Table Expressions

    0 讨论(0)
提交回复
热议问题