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匹配的数据的查询。例如,当我删除带有1个值的employeeID时,它应删除managerID为1并再次递归检查managerID 1 = 273 EmployeeID并比较该273 ManagerID并找出employeeID为16,依此类推。假设我们递归地删除子id与parentid相比,就像在购物车中一样,当我们删除父类时,它会递归删除所有产品及其子产品。
答案 0 :(得分:5)
您可以尝试类似
的内容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)