SQL CTE Recursion: Returning Parent Records

后端 未结 1 1439
我寻月下人不归
我寻月下人不归 2021-01-19 01:10

I am currently running a CTE query to recursively build an employee hierarchy from an employees table similar to what most recursive examples demonstrate. Where I am stuck

相关标签:
1条回答
  • 2021-01-19 02:00

    Are you looking for a query to return a variable number of columns, depending on the depth of hierarchy? Or just a concatenated string in one field?

    Here's a minor change to your query that will get Eric and anyone above him in the hierarchy.

    WITH    employeeMaster
          AS ( SELECT   p.EmployeeID ,
                        p.MgrID ,
                        p.NAME
               FROM     Employees p
               WHERE    p.NAME = 'Eric'
               UNION ALL
               SELECT   c.EmployeeID ,
                        c.MgrID ,
                        c.NAME
               FROM     employeeMaster cte
                        INNER JOIN Employees c ON c.EmployeeID = cte.MgrID
             )
    SELECT  *
    FROM    employeeMaster m
    
    0 讨论(0)
提交回复
热议问题