T-SQL 101: 32 Repeating T-SQL batches with GO n

T-SQL 101: 32 Repeating T-SQL batches with GO n

In my last T-SQL 101 post, I mentioned that GO was just a word that’s used to separate batches. In fact, it’s not a SQL word at all. If you actually send the word GO to the server, it wouldn’t know what you’re talking about.

I mentioned that the word is only understood by the program that you type the script into. SSMS also allows us to make use of another additional trick in relation to GO.

I can add a number after the word GO, and SSMS will execute the batch that number of times.

Here’s an example:

First up, notice that the 10 is underlined with a red squiggle. The T-SQL intellisense has no idea what’s going on with the number.

But when we execute it, SSMS outputs Beginning execution loop, then it sends the batch containing PRINT ‘HELLO’; to the server 10 times (one at a time), then prints Batch execution completed 10 times.

SSMS is doing all the work. SQL Server just sees 10 separate batches sent to it.

This can be useful if you need to run a command many times.

Learning T-SQL

It’s worth your while becoming proficient in SQL. If you’d like to learn a lot about T-SQL in a hurry, our Writing T-SQL Queries for SQL Server course is online, on-demand, and low cost.

2019-08-26