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, landed on to MSDN page for the GO statement. And to my surprise 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 following two simple examples:

Example 1:

PRINT 'Hello'
GO 5

Result of Executing the above statement

Beginning execution loop
Hello
Hello
Hello
Hello
Hello
Batch execution completed 5 times. 

Example 2: In this example we are creating a Test table and inserting 5 records in it.

 

This statement is very handy for testing purposes and dev tasks, such as for testing purpose if we need to insert millions together records we can achieve this with simple two statement as explained in the above examples.

Please correct me, if my understanding is wrong. Comments are always welcome, hope this article helped you.

9 thoughts on “GO Statement can also be used to excute batch of T-Sql statement multiple times

Leave a Reply

Your email address will not be published. Required fields are marked *