Tuesday, November 24, 2020

SQL - How to delete large numbers of records without locking tables

https://stackoverflow.com/questions/20499270/delete-statements-locks-table#:~:text=As%20others%20have%20pointed%20out,deletes%20until%20it%20is%20done.

  • If you delete more than around 5000 records, the entire table gets locked for the duration of the delete
  • If you split up the job into a loop of 1000 record delete bursts, it never locks the entire table


 declare @MoreRowsToDelete bit

set @MoreRowsToDelete = 1

while @MoreRowsToDelete = 1

begin

    delete top (1000) CRONUS$Preaction from CRONUS$Preaction where Date < '2020-07-01 00:00:00.000'

    if not exists (select top 1 * from CRONUS$Preaction where Date < '2020-07-01 00:00:00.000')

        set @MoreRowsToDelete = 0

end

No comments:

Post a Comment