我有一个包含以下字段的表
•Supervisorid •EMPID 这就像推荐计划一样。一个人可以参考他下面的3个人,即3个是指三个人即4 5 8同样4指9 10和11同样8指的是12,13就是这样..
我想要一个查询来获取Supervisor 3下的所有EmpId
答案 0 :(得分:0)
检查this。它使用递归存储过程,因此引用级别将受到限制。
非递归存储过程调用solution。
使用SQL2005,您可以使用使用公用表表达式的递归查询:
WITH Report(Supervisorid , Empid , Title, Level)
AS
(
-- Anchor member definition
SELECT e.Supervisorid , e.Empid , e.Title, 0 AS Level
FROM dbo.MyEmployees AS e
WHERE Supervisorid = 3
UNION ALL
-- Recursive member definition
SELECT e.Supervisorid , e.Empid , e.Title, Level + 1
FROM dbo.MyEmployees AS e
INNER JOIN Report AS d
ON e.Supervisorid = d.Empid
)
-- Statement that executes the CTE
SELECT Supervisorid , Empid , Title, Level
FROM Report;