SQL Server:查找层次结构链断裂的位置

时间:2018-05-16 19:52:27

标签: sql sql-server recursive-query

我在表格中拥有超过70,000个员工数据。它看起来像这样:

+----------------+----------------------+----------+
| EmployeeId     | name                 | ManagerID|
+----------------+----------------------+----------+
|              1 | Iron Man             | 2        |
|              2 | Batman               | 4        |
|              3 | Superman             | 2000     |
|              4 | Captain America      | 3        |    
+----------------+----------------------+----------+

此处,超人的ManagerID无效,因为ManagerID = 2000列中不存在EmployeeID。为了给超人分配一个新的ManagerID,我需要找出他所处的层次结构。我知道它应该是一些递归查询,但我遇到了很多困难。有人可以帮忙吗?非常感谢你!

2 个答案:

答案 0 :(得分:0)

为了找出损坏的记录,您可以使用子查询

select * 
from table t
where not exists (select 1 from table where EmployeeId = t.ManagerID);

答案 1 :(得分:0)

这可能会帮助您入门。

CREATE TABLE Employees ( EmployeeID INT, Name VARCHAR(200), ManagerID INT )
INSERT INTO Employees ( EmployeeID, Name, ManagerID ) VALUES ( 1, 'Iron Man', 2 ), ( 2, 'Batman', 4 ), ( 3, 'Superman', 2000 ), (4, 'Captain America', 3 )

WITH Relationships ( ManagerID, Name, EmployeeID ) AS
(
  SELECT
    ManagerID, Name, EmployeeID
  FROM
    Employees
  WHERE
    ManagerID IN ( SELECT EmployeeID FROM Employees )
  UNION ALL
  SELECT
    Employees.ManagerID, Relationships.Name, Relationships.EmployeeID
  FROM
    Employees,
    relationships
  WHERE
    Employees.EmployeeID = Relationships.ManagerID
)
SELECT
  EmployeeID, Name, ManagerID
FROM
  Relationships
WHERE
  EmployeeID = 1 -- Iron Man
OPTION ( MAXRECURSION 25000 )

将“EmployeeID = 1”替换为您要定位的员工ID。它返回的行数是级别。您可以将ROW_NUM添加到最外面的查询以获取该值。