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を手伝ってくれませんか?

この例では、結果は次のようになります。

Earl
Sue
Mac
4

2 に答える 2

4

共通テーブル式を使用した再帰クエリをご覧ください

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-データ

于 2012-10-13T08:37:13.290 に答える
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
于 2012-10-13T01:21:49.950 に答える