层次查询的SQL Server 2008(hierarchy query sql server 20

2019-09-24 01:37发布

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

Answer 1:

看看递归查询使用公用表表达式

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-日期



Answer 2:

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


文章来源: hierarchy query sql server 2008