Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

GO Statement can also be used to Execute Batch of T-SQL Statement Multiple Times

5.00/5 (1 vote)
26 May 2013CPOL 29.9K  
GO Statement can also be used to execute batch of T-SQL statement multiple times

Introduction

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.

Please correct me if my understanding is wrong. Comments are always welcome, hope this tip helped you. Visit my blog SqlHints.com for such SQL tips/tricks and articles.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)