In T-SQL, the keyword “GO” is the default batch separator.
For example:
DELETE
FROM
ErrorLog
WHERE
ErrorTime < ’2008-01-01′
GO
But what if you have billions of rows in the “ErrorLog” table and you need to delete them a batch at a time so that you don’t lock up the entire table? You can use the “TOP” operator to specify the batch size and then specify an integer value that follows the “GO” keyword specifying the number of batches to execute.
For example:
DELETE
TOP(100000)
FROM
ErrorLog
WHERE
ErrorTime < ’2008-01-01′
GO 10000
In this example, we specify the batch size to 100,000 by using the “TOP” operator and then we specify the number of times to execute this batch by specifying 10,000 after the “GO” keyword. This block of code will now execute 10,000 times each time deleting 100,000 records from the “ErrorLog” table.
Specifying the batch count after the “GO” keyword is a very powerful yet frequently overlooked tool available to you in SQL Server 2005 & 2008. It allows you to specify a single number to execute a block of code in a loop without setting up counters and BEGIN / END blocks for simple blocks of code. This is a great addition to anyone’s SQL toolkit.
Posted in Programming SQL Server, SQL Server 2005, SQL Server 2008, T-SQL Tagged: SQL Server, SQL Server 2005, SQL Server 2008, SQL Server Expert, SQL Server Recovery
