Rod
Rod

Reputation: 15477

hierarchy query sql server 2008

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

Answers (2)

Mikael Eriksson
Mikael Eriksson

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

SE-Data

Upvotes: 4

Z .
Z .

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

Related Questions