79514992

Date: 2025-03-17 15:20:37
Score: 0.5
Natty:
Report link

The recursive query you are using is correct only need to modify 2 things:

  1. Join - COALESCE(e.ManagerID, e.TeamLeadID)

  2. Parameter - DECLARE @EMPId INT = 1

here is the query you required:

DECLARE @EMPId INT = 1

;WITH Hierarchy AS 
(
    SELECT *  
    FROM dbo.Employee  
    WHERE employeeid = @EMPId

    UNION ALL  

    SELECT e.*
    FROM dbo.Employee e 
    INNER JOIN Hierarchy h 
        ON h.employeeid = COALESCE(e.ManagerID, e.TeamLeadID)
)  
SELECT *
FROM Hierarchy H
ORDER BY COALESCE(ManagerID, TeamLeadID)
OPTION (MAXRECURSION 1000);

this will give output as per your requirements:

  1. If Employee ID = 1 ('M1')

    EmployeeId = 1

  2. If Employee ID = 2 ('M2')

    EmployeeId = 2

  3. If Employee ID = 10 ('T2_2')

    EmployeeId = 10

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Harsh Varde