在sql查询下查找单个上级下的所有下属

时间:2011-12-02 04:35:00

标签: sql sql-server sql-server-2005 recursion common-table-expression

我的表包含三列,值如下所示

Emp_ID |  Emp_Name   |  Emp_Manager_ID
========================================
1      |  Admin      |   Null         
2      |  John       |   1            
3      |  Sam        |   2             
4      |  Mike       |   2            
5      |  Jeff       |   4            
6      |  Ben        |   3            
7      |  Vicky      |   5

参数id @Emp_ID = 2 找到给定Emp_Id下所有下属的预期结果 所以结果应该是所有EmpID 3,4,5,6,7 因为2是3,4的管理者,3是6的经理,4是5的经理,5是7的经理

1 个答案:

答案 0 :(得分:7)

使用Recursing CTE。这当前返回所有三列。如果您不需要该信息,请从Emp_Name移除Emp_Manager_IDSELECT

WITH Subordinates AS
(
   SELECT e.Emp_ID, e.Emp_Name, e.Emp_Manager_ID
   FROM Employee AS e
   WHERE e.Emp_Manager_ID = 2

   UNION ALL

   SELECT e.Emp_ID, e.Emp_Name, e.Emp_Manager_ID
   FROM Employee AS e
   INNER JOIN Subordinates AS sub ON e.Emp_Manager_ID = sub.Emp_ID
)
SELECT s.Emp_ID, s.Emp_Name, s.Emp_Manager_ID
FROM Subordinates AS s

Example of query running using Employee_ID = 1: