Wednesday, November 30, 2011

GO Statement can also be used to excute batch of T-SQL statement multiple times

Till recently, I was under the impression that GO statement’s sole purpose is to convey to the SQL Server the end of a batch of T-SQL Statements. But recently while searching for some SQL feature details, I landed on to the MSDN page for the GO statement. And to my surprise, I observed that GO statement also has an integer optional parameter, this parameter value signals SQL Server to execute the batch of T-SQL Statement prior to the GO statement to be executed for the specified number of times.

Let us understand this with the following simple example:
PRINT 'Hello'
GO 5
Result of executing the above statement is as follows:
Beginning execution loop
Hello
Hello
Hello
Hello
Hello
Batch execution completed 5 times
This statement is very handy for testing purposes and dev tasks, such as for testing purpose if we need to insert millions of records together, we can achieve this with simple two statements as explained in the above example.