0

我有下表:

ID      Emp_Name     Manager_ID
101     Ken          NULL
102     Terri        101
103     Roberto      101
104     Rob          102
105     Gail         102
106     Jossef       103
107     Dylan        103
108     Diane        105
109     Gigi         105
110     Michael      106

例如,我需要获取“106 Josef”的所有经理,结果必须是:

106     Josef        103
103     Roberto      101
101     Ken          NULL

执行此操作的最佳 sql server 查询是什么

4

2 回答 2

1

我的递归 CTE非常生疏,我没有方便测试的数据库,这会更容易走向另一个方向(经理对报告者),但我认为这会做到,或者至少接近:

declare @EmpID int;
set @EmpId = 106;

with IDs (ID, Manager_ID) As (
     select ID, Manager_ID FROM Employees WHERE ID = @EmpID
     UNION ALL
     SELECT ID, Manager_ID 
     FROM Employees e
     LEFT JOIN ManagerIDs m on e.ID = m.Manager_ID
     WHERE e.ID IS NOT NULL
)
SELECT e.*
FROM IDs i
INNER JOIN Employees e on e.ID = i.ID;
于 2013-10-04T23:24:04.363 回答
1

您可以执行一个 while 循环来遍历三个管理器,直到您可以获取主节点,在每次迭代中,代码都会在临时表中插入行。这是一个例子。

DECLARE @employeeId  int
DECLARE @managerId int

SET @employeeId=106
SET @managerId=(SELECT Manager_ID FROM Employees WHERE ID=@employeeId)

DECLARE @tableEmployee as TABLE 
(
ID int,
NAME varchar(100),
MANID INT
)
INSERT INTO @tableEmployee SELECT * FROM Employees WHERE ID=@employeeId

WHILE @managerId is not null
BEGIN
INSERT INTO @tableEmployee SELECT * FROM Employees WHERE ID=@managerId
SET @managerId=(SELECT Manager_ID FROM Employees WHERE ID=@managerId)
END
SELECT * FROM @tableEmployee
GO

我认为不是最好的,但有效,我希望这会有所帮助:)。

于 2013-10-05T05:23:00.620 回答