情景:
示例:
DECLARE @CustomerList TABLE (CustomerID bigint)
INSERT INTO @CustomerList SELECT CustomerID FROM TableA WHERE CustomerID = @ParameterID
WHILE (SELECT COUNT(*) FROM @CustomerList) > 0
BEGIN
DELETE FROM [TableB]
WHERE [CustomerID] = @CustomerList.CustomerID -- challenge
END
挑战:
更新
答案 0 :(得分:4)
为什么要循环?
Delete From [Table B]
Where [CustomerID] in (Select CustomerID from TableA where SomeCondition=true)
好的,然后支持多次删除。您可以保留表变量
DECLARE @CustomerList TABLE (CustomerID bigint)
INSERT INTO @CustomerList SELECT CustomerID FROM TableA WHERE CustomerID = @ParameterID
Delete From [Table B] Where [CustomerID] in (Select CustomerID from @CustomerList)
Delete From [Table C] Where [CustomerID] in (Select CustomerID from @CustomerList)
答案 1 :(得分:1)
为什么你不能使用join而不是while。像下面的东西。
DELETE t
FROM TableB as t
join @CustomerList as c
on t.CustomerID = C.CustomerID;
答案 2 :(得分:1)
我不确定你为什么需要临时表或循环。联接应该有效。
示例:
DELETE B
FROM TableB B
INNER JOIN TableA A
ON B.CustomerID=A.CustomerID
WHERE A.CustomerID = @ParameterID