VSO
VSO

Reputation: 12646

Use Go After 'Use [Database_Name]?

A common pattern that I see is:

USE Name_Of_My_Database
GO

As far as I can tell, there is no point to this, is there? I have tried looking for the answer in the places listed below, and it's absent:

What is the use of GO in SQL Server Management Studio & Transact SQL?

In SQL Server, when should you use GO and when should you use semi-colon ;?

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-go

Edit: No, it's not a duplicate, this question is more specific - I didn't find the information I needed in the linked question, though I read it before posting this.

Upvotes: 1

Views: 2074

Answers (2)

pmbAustin
pmbAustin

Reputation: 3970

I set my SSMS Scripting Options to not script USE statements. I find them pointless as well, in general.

"GO" isn't a SQL command, it's just a batch separator... it's an SSMS feature (or ISQL/OSQL feature), not a SQL Server feature. It's a way to have one text file contain multiple batches of SQL to send to SQL Server.

Upvotes: 0

Siyual
Siyual

Reputation: 16917

There are two big differences between GO and ;:

  1. GO splits the script into different batches.
  2. ; is a statement terminator.

Using GO after a USE DatabaseName is necessary when the following statement requires it to be the first statement in a batch. As an example, the following code will fail:

Use SomeDatabase

Create Procedure spSomeProcedure
As Begin
    Select 1
End

Msg 111, Level 15, State 1, Procedure spSomeProcedure, Line 4
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.

But adding a GO between them will allow the statement to run:

Use SomeDatabase
Go

Create Procedure spSomeProcedure
As Begin
    Select 1
End

Command(s) completed successfully.

Upvotes: 4

Related Questions