How to update large table with millions of rows in SQL Server?

后端 未结 6 883
面向向阳花
面向向阳花 2020-11-28 10:07

I\'ve an UPDATE statement which can update more than million records. I want to update them in batches of 1000 or 10000. I tried with @@ROWCOUNT bu

6条回答
  •  时光说笑
    2020-11-28 10:23

    This is a more efficient version of the solution from @Kramb. The existence check is redundant as the update where clause already handles this. Instead you just grab the rowcount and compare to batchsize.

    Also note @Kramb solution didn't filter out already updated rows from the next iteration hence it would be an infinite loop.

    Also uses the modern batch size syntax instead of using rowcount.

    DECLARE @batchSize INT, @rowsUpdated INT
    SET @batchSize = 1000;
    SET @rowsUpdated = @batchSize; -- Initialise for the while loop entry
    
    WHILE (@batchSize = @rowsUpdated)
    BEGIN
        UPDATE TOP (@batchSize) TableName
        SET Value = 'abc1'
        WHERE Parameter1 = 'abc' AND Parameter2 = 123 and Value <> 'abc1';
    
        SET @rowsUpdated = @@ROWCOUNT;
    END
    

提交回复
热议问题