层次结构查询sql server 2008

时间:2012-10-13 01:09:47

标签: 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

你能帮助我使用sql来让员工和管理人员上链吗?

在此示例中,结果将是

Earl
Sue
Mac

2 个答案:

答案 0 :(得分: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 :(得分: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