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

后端 未结 8 1433
死守一世寂寞
死守一世寂寞 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 01:45

    You should try to give it a ROWLOCK hint so it will not lock the entire table. However, if you delete a lot of rows lock escalation will occur.

    Also, make sure you have a non-clustered filtered index (only for 1 values) on the toDelete column. If possible make it a bit column, not varchar (or what it is now).

    DELETE FROM Sales WITH(ROWLOCK) WHERE toDelete='1'
    

    Ultimately, you can try to iterate over the table and delete in chunks.

    Updated

    Since while loops and chunk deletes are the new pink here, I'll throw in my version too (combined with my previous answer):

    SET ROWCOUNT 100
    DELETE FROM Sales WITH(ROWLOCK) WHERE toDelete='1'
    
    WHILE @@rowcount > 0
    BEGIN
      SET ROWCOUNT 100
      DELETE FROM Sales WITH(ROWLOCK) WHERE toDelete='1'  
    END
    

提交回复
热议问题