Petr
Petr

Reputation: 7957

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

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!

Upvotes: 20

Views: 22205

Answers (2)

Cade Roux
Cade Roux

Reputation: 89661

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.

Upvotes: 20

Incognito
Incognito

Reputation: 16577

It signals the end of a batch of Transact-SQL statements to the SQL Server utilities. You can check here for more details : GO (Transact-SQL)

Upvotes: 2

Related Questions