Using GO in SSMS versus not – what is the difference

You might see GO used in SQL text. The GO command marks the end of a batch.  As a result, any statements executed after this are part of a new batch.  This also means any context of the previous batch is missing.  Take for example the following:

DECLARE @CustomerID INT
SET @CustomerID = 123152
SELECT * FROM Customer WHERE CustomerID = @CustomerID
GO
SELECT * FROM CustomerAddress WHERE CustomerID = @CustomerID
GO

The above will fail because @CustomerID is outside the scope of the second statement. 

If the GO is removed the statement will run without error:
DECLARE @CustomerID INT
SET @CustomerID = 123152
SELECT * FROM Customer WHERE CustomerID = @CustomerID
SELECT * FROM CustomerAddress WHERE CustomerID = @CustomerID
GO

It should be noted, that if there is not a GO statement specified it will behave similar to the prior example where there is one GO at the bottom of the query text.

Final Thoughts

This will only work in tools such as SSMS and SQLCMD – if you try using GO in code using ADO or JDBC this will generate an error.  Also, the semicolon ; doesn’t do much other than delimiting statements – it does not separate batches.  I’ve rarely seen the need for the explicit use for a semicolon with the exception of using a CTE where a different statement precedes it.

Leave a Reply

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