2012-10-13 152 views
1
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 

你能幫我用sql來讓員工和經理上鍊嗎?層次結構查詢sql server 2008

在這個例子中,結果將是

Earl 
Sue 
Mac 

回答

4

看一看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

1
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