SQL Batched Delete

后端 未结 9 1915
星月不相逢
星月不相逢 2021-02-20 04:29

I have a table in SQL Server 2005 which has approx 4 billion rows in it. I need to delete approximately 2 billion of these rows. If I try and do it in a single transaction, th

9条回答
  •  佛祖请我去吃肉
    2021-02-20 04:59

    In addition to putting this in a batch with a statement to truncate the log, you also might want to try these tricks:

    • Add criteria that matches the first column in your clustered index in addition to your other criteria
    • Drop any indexes from the table and then put them back after the delete is done if that's possible and won't interfere with anything else going on in the DB, but KEEP the clustered index

    For the first point above, for example, if your PK is clustered then find a range which approximately matches the number of rows that you want to delete each batch and use that:

    DECLARE @max_id INT, @start_id INT, @end_id INT, @interval INT
    SELECT @start_id = MIN(id), @max_id = MAX(id) FROM My_Table
    SET @interval = 100000  -- You need to determine the right number here
    SET @end_id = @start_id + @interval
    
    WHILE (@start_id <= @max_id)
    BEGIN
         DELETE FROM My_Table WHERE id BETWEEN @start_id AND @end_id AND 
    
         SET @start_id = @end_id + 1
         SET @end_id = @end_id + @interval
    END
    

提交回复
热议问题