Programmer's Rules

SQL Server

When to use GO batch SQL separator in SQL Server

Rules for SQL code that requires multiple batches

SQL Serverjob interviewTransact-SQL70-761

GO is not a Transact-SQL command but is recognized by the sqlcmd and SQL Server Management Studio.

It is used to separate batches when it is required to create or manipulate new objects. For example, it is necessary to use GO command in the following code:

Otherwise you will get an error "'CREATE VIEW' must be the first statement in a query batch."

When not to use GO command.

Because user-defined variables are treated as local to the batch in which they are declared they cannot be separated by concluding them with the GO keyword. SQL Server runs each batch in its entirety before it starts the next one.

The following example will cause an error because the above:

Additionally, the GO command cannot occupy the same line as a Transact-SQL Statement; The following code will cause an error:

Tutorial statistics