Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is "GO" after USE db" in T-SQL examples?

Tags:

sql

sql-server

Looking at the msdn, there was an example on "GO" command. Why there is:

USE somedb
GO
...
...

It it neccesary to select db in different batch? Thanks for explanation!

like image 223
Petr Avatar asked May 31 '10 10:05

Petr


People also ask

What is the use of GO in T-SQL?

GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor. SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server.

What is the purpose of the GO batch separator?

You can use the GO command to separate batches of SQL commands in database scripts. The GO command executes all the SQL statements in the current batch. A batch is defined as all the SQL commands since the previous GO command, or since the start of the script if this is the first GO command in the script.

What does the GO command do?

The GO command is actually not a SQL command, but an SSMS command. It tells SSMS to send the previous commands as a batch. So the difference is your first code will send it all at once, while the second will send in four batches.

Is GO necessary in SQL?

They're not strictly required - they're just instructions for the SQL Server Management Studio to execute the statements up to this point now and then keep on going. GO is not a T-SQL keyword or anything - it's just an instruction that works in SSMS.


1 Answers

Is it necessary to select db in different batch?

No, however, some commands have to be the first statement in the batch.

Examples include CREATE VIEW, CREATE PROCEDURE and CREATE TRIGGER.

Thus if you want to do:

USE DB

CREATE VIEW X AS SELECT * FROM Y

Then you need to do:

USE DB
GO

CREATE VIEW X AS SELECT * FROM Y

If you are only running one USE DB statement, the GO has no usefulness.

Some commands do not require that they are the first statement in a batch:

USE DB
SELECT * FROM X

Sometimes in code generation, all the GO commands might not be necessary, but it's just easier to generate them.

like image 109
Cade Roux Avatar answered Oct 07 '22 05:10

Cade Roux