3
ManagerID EmployeeID Title                         Level
--------- ---------- ----------------------------- ------
NULL      1          Chief Executive Officer       0
1         273        Vice President of Sales       1
273       16         Marketing Manager             2
273       274        North American Sales Manager  2
273       285        Pacific Sales Manager         2
16        23         Marketing Specialist          3
274       275        Sales Representative          3
274       276        Sales Representative          3
285       286        Sales Representative          3

我想要一个递归删除与employeeID 和managerID 匹配的数据的查询。

例如,当我删除值为 1 的员工 ID 时,它应该删除 1 的 managerID 并再次递归检查 managerID 1 = 273 EmployeeID 并比较该 273 ManagerID 并找出 16 的员工 ID 等等。

假设我们递归地删除子 id 与 parentid 相比,就像在购物车中一样,当我们删除父类别时,它会递归地删除所有产品及其子产品。

4

1 回答 1

7

你可以尝试类似的东西

DECLARE @EmployeeID INT = 1
;WITH Vals AS (
  SELECT *
  FROM Table1
  WHERE EmployeeID = @EmployeeID
  UNION ALL
  SELECT t1.*
  FROM Table1 t1 INNER JOIN
  Vals v ON t1.ManagerID = v.EmployeeID
 )
DELETE
FROM Table1
WHERE EmployeeID IN (SELECT EmployeeID FROM Vals)

SQL 小提琴演示

于 2013-09-09T18:24:11.297 回答