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.

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

  1. You basic assumption that “GO” is “a statement’s sole purpose is to convey to the Sql Server” IS WRONG. “Go” has nothing to do with Transact SQL or with the SQL Server! This is a Batch separator in the client side, used by applications like SSMS.

    You can change the configuration of SSMS and choose any separator that you want including your own name:
    Go to “Tools” –> “Options” -> select “Query Execution” -> here you have option to configure the Batch separator

    * During April First several years ago I change the configuration on my team’s machines and let them find the issue 🙂

Leave a Reply

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