I am using SQL Server.
My table is called Employees.
It looks like this:
x
EmpID ManagerID EmpName
----- --------- -------
1 NULL Ali
2 1 Mike
3 1 Tom
4 2 Kim
5 2 Rob
6 3 Lay
7 5 Paul
8 7 Sam
9 6 Bin
I am trying to build a query that returns all parents of the children
So the query would return the parents of Bin and Sam are
Bin, Lay, Tom, Ali
Sam, Paul, Rob, Mike, Ali
I tried this but wasn’t successful
SELECT *
FROM Employees A
LEFT OUTER JOIN Employees B ON A.ParentID = B.EmpID
WHERE A.EmpID IN (8,9)
but this can only work for 1 parent
How can I get the whole list of parents (managers)?
Advertisement
Answer
Use recursive cte
WITH Parent AS
(
SELECT *
FROM Employees WHERE EmpID IN (8,9)
UNION ALL
SELECT emp.*
FROM Employees emp JOIN Parent ON emp.EmpID = Parent.ManagerID
)
SELECT distinct * FROM Parent