通过临时表循环获取记录值

时间:2016-09-26 20:30:25

标签: sql sql-server tsql

情景

  1. 从一个TableA中选择记录
  2. 遍历表值
  3. 根据每个记录的值
  4. 从另一个表(TableB)中删除

    示例

    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
    

    挑战

    • 传递每个循环的CustomerID值

    更新

    • 想要使用循环的原因是有多个要执行的删除语句

3 个答案:

答案 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