USE of GO in SQL Server

GO is interpreted by SQL Server utilities as a signal to deliver the current batch of Transact-SQL statements to a SQL Server instance. All statements entered since the last GO, or since the beginning of the ad hoc session or script if this is the first GO, make up the current batch of statements.

To put it simply, SQL commands are grouped into batches and delivered to the server collectively using the GO command.

To notify the SQL Server engine that the prior statement is unrelated to the present one, you must provide GO when you are not using new query windows for distinct jobs. Below are some examples.

Example-1

CREATE DATABASE dbTest
GO

USE dbTest
Go

CREATE TABLE…

In the above example, GO is recommended to switch from database creation to bringing the database into usage. Also to jump into further statements.

Example-2

ALTER PROCEDURE uspUpdateValue
AS
BEGIN TRY
    DECLARE @ErrorMessage VARCHAR(100)
    SET @ErrorMessage = ‘An error while updating Table t’
    UPDATE t SET value = ‘abcd’
END TRY
BEGIN CATCH
RAISERROR(@ErrorMessage, 1, 1)
END CATCH;
GO
— Execution
EXEC uspUpdateValue

GO is required at the specified point if you modify an already-existing stored procedure, if you have an execution statement open in the same query window, and if you intend to execute both statements simultaneously. If not, the execution statement will be included within the procedure’s code.

Example-3

CREATE VIEW must be the first statement in a query batch.

If you have any piece of code before the CREATE VIEW statement, use GO. Otherwise, you’ll end up having the above-specified error message.

Example-4

CREATE FUNCTION statement must be the first statement in a query batch
CREATE/ALTER PROCEDURE statement must be the first statement in a query batch

Not only for views, the same rule applies to Stored procedures and user-defined functions. In a batch, the statements CREATE DEFAULT, CREATE FUNCTION, CREATE PROCEDURE, CREATE RULE, CREATE SCHEMA, CREATE TRIGGER, and CREATE VIEW cannot be mixed with other statements.

In summary, it is a good practice to include a GO statement when you are transitioning between tasks.

Happy learning!!

Leave a Reply