Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the meaning of the GO-statement in TSQL

Tags:

sql

tsql

I'm new to TSQL and wondering what the GO statement really means. To me it just seems thrown in there where ever it seems to fit.

I guess it somehow tells sql server to run the previous statement? What happens if you don't use them at all? Could someone give an example where a statement will break if I don't use a GO.

Please elaborate.

like image 714
picknick Avatar asked May 25 '10 13:05

picknick


People also ask

Is Go required in SQL?

The query requires a GO at the end to inform to sqlcmd that it is the end of the batch. Without the GO, the query will not be executed.

What is go in SQL stored procedure?

GO is not a T-SQL command. It is a batch delimiter but it is parsed and processed by the front end query tool - e.g. ISQL, OSQL, ISQL/W etc. When the front-end sees a go it sends the previous batch of SQL to SQL Server for processing.

Is go the same as in SQL?

GO is not actually a T-SQL command. The GO command was introduced by Microsoft tools as a way to separate batch statements such as the end of a stored procedure. GO is supported by the Microsoft SQL stack tools but is not formally part of other tools.

Is go a statement?

The GO command isn't a Transact-SQL statement, but a special command recognized by several MS utilities including SQL Server Management Studio code editor. The GO command is used to group SQL commands into batches which are sent to the server together.


3 Answers

It is a batch terminator

this will break

declare @i int
set @i =5

declare @i int
set @i =6

Select @i

Msg 134, Level 15, State 1, Line 5 The variable name '@i' has already been declared. Variable names must be unique within a query batch or stored procedure.

this will work

declare @i int
set @i =5

go
declare @i int
set @i =6

Select @i
like image 158
SQLMenace Avatar answered Oct 19 '22 11:10

SQLMenace


It ends the batch.

It is rarely needed and is used far more often than it should be. One valid place is in stored proc programming where you first do a check if the proc exists and drop it if it doesn't. Then you use a go statement to end the batch because the create proc statement must be the first statement of a batch.

like image 44
HLGEM Avatar answered Oct 19 '22 10:10

HLGEM


By the way. It isn't actually a TSQL command. It is just used by Microsoft DB tools to separate two batches of commands.

In fact you can configure it to be a different word in SSMS if you want to under the Optionss..Batch separation preference setting.

The main place this distinction is important is that SQL Will choke on GO statement if you try to use them in queries through a database connection from code, for example through ADO.NET.

like image 36
JohnFx Avatar answered Oct 19 '22 10:10

JohnFx