Reputation: 15477
EmployeeId, Name, ManagerId
1,Mac Manager, null
2,Sue Supervisor, 1
3,Earl Employee, 2
4,Sam Supervisor, 1
5,Ella Employee, 4
Given: Employee Id = 3
Can you help me with sql to get the employee plus managers up the chain?
In this example the results would be
Earl
Sue
Mac
Upvotes: 1
Views: 2743
Reputation: 139010
Have a look at Recursive Queries Using Common Table Expressions
declare @EmpID int = 3;
with C as
(
select E.EmployeeId,
E.Name,
E.ManagerId
from YourTable as E
where E.EmployeeId = @EmpID
union all
select E.EmployeeId,
E.Name,
E.ManagerId
from YourTable as E
inner join C
on E.EmployeeId = C.ManagerId
)
select C.Name
from C
Upvotes: 4
Reputation: 12837
declare @current int
set @current = @empid
while @current is not null begin
-- do something with it
print @current
set @current = (select ManagerId from table where EmployeeId = @current)
end
Upvotes: 1