Deleting Rows in Chunks in Sql Server In this recipe, I show you how to modify data in blocks of rows in multiple executions, instead of an entire result set in one large transaction. First, I create an example deletion table for this example: SELECT * INTO Production.Example_BillOfMaterials FROM Production.BillOfMaterials Next, all rows will be deleted from the table in 500 row chunks: WHILE (SELECT COUNT(*)FROM Production.Example_BillOfMaterials)> 0 BEGIN DELETE TOP(500) FROM Production.Example_BillOfMaterials END (500 row(s) affected) (500 row(s) affected) (500 row(s) affected) (500 row(s) affected) (500 row(s) affected) (179 row(s) affected) In this example, I used a WHILE condition to keep executing the DELETE while the count of rows in the table was greater than zero . WHILE (SELECT COUNT(*)FROM Production.Example_BillOfMaterials)> 0 BEGIN Next was the DELETE, followed by the TOP clause, and the row limitation in parentheses: DELETE TOP(500) FROM Production.BillOfMaterials This recipe didn't use a WHERE clause, so no filtering was applied and all rows were deleted from the table—but only in 500 row chunks. Once the WHILE condition no longer evaluated to TRUE, the loop ended. After executing, the row counts affected in each batch were displayed. The first five batches deleted 500 rows, and the last batch deletes the remaining 179 rows. |