How to efficiently delete rows while NOT using Truncate Table in a 500,000+ rows table

后端 未结 8 1394
死守一世寂寞
死守一世寂寞 2020-11-30 01:30

Let\'s say we have table Sales with 30 columns and 500,000 rows. I would like to delete 400,000 in the table (those where \"toDelete=\'1\'\").

相关标签:
8条回答
  • 2020-11-30 02:02

    What you want is batch processing.

    While (select Count(*) from sales where toDelete =1) >0
    BEGIN
    Delete from sales where SalesID in
    (select top 1000 salesId from sales where toDelete = 1)
    END
    

    Of course you can experiment which is the best value to use for the batch, I've used from 500 - 50000 depending on the table. If you use cascade delete, you will probably need a smaller number as you have those child records to delete.

    0 讨论(0)
  • 2020-11-30 02:03

    My own take on this functionality would be as follows. This way there is no repeated code and you can manage your chunk size.

    DECLARE @DeleteChunk INT = 10000
    DECLARE @rowcount INT = 1
    
    WHILE @rowcount > 0
    BEGIN
    
      DELETE TOP (@DeleteChunk) FROM Sales WITH(ROWLOCK)
    
      SELECT @rowcount = @@RowCount
    END
    
    0 讨论(0)
提交回复
热议问题