sql server查询选择具有特定子项的父项

时间:2013-10-04 23:05:50

标签: asp.net sql sql-server database

我有下表:

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查询是什么

2 个答案:

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

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

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