Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ; and GO in stored procedure in SQL Server?

Tags:

What is the difference between ; and GO in stored procedure in SQL Server ?

Actually, if I have a stored procedure in SQL server and wanna to put t separate queries inside it which the first one just calculates number of records (count) and the second one selects some records based on some conditions, then what should I use between that two queries?

Go or ;

like image 975
odiseh Avatar asked Feb 22 '10 11:02

odiseh


People also ask

What is the difference between and go in SQL?

Under SQL Server TSQL (2005 - 2016) bear in mind that: Semicolon (;) is a block terminator. GO is a batch terminator.

What is go in SQL stored procedure?

Using GO in SQL Server GO is not a SQL keyword. It's a batch separator used by the SQL Server Management Studio code editor tool for when more than one SQL Statement is entered in the Query window. Then Go separates the SQL statements. We can say that Go is used as a separator between transact SQL Statements.

Why we use go in stored procedure?

The GO command indicates the end of a batch of SQL Statements and a stored procedure is itself a batch of statements encapsulated as one routine. You can be confident that each statement will run sequentially as this is the behaviour of SQL Server.

Can you put a go in a stored procedure?

You can't use GO inside a stored procedure. If you would try, the definition of the procedure will end there, and the rest will be a separate batch.


2 Answers

; just ends the statement.

GO is not a statement but a command to the server to commit the current batch to the Database. It creates a stop inside the transaction.

http://msdn.microsoft.com/en-us/library/ms188037.aspx

(Update, thanks for the comments):
GO is a statement intended for the Management studio as far as I know, maybe to other tools as well.

like image 196
Faruz Avatar answered Sep 19 '22 18:09

Faruz


The semicolon separates queries, the GO command separates batches. (Also GO is not a T-SQL command, it's a command recognised by the sqlcmd and osql utilities and Management Studio.)

You can't use GO inside a stored procedure. If you would try, the definition of the procedure will end there, and the rest will be a separate batch.

A local variable has the scope of the batch, so after a GO command you can't use local variables declared before the GO command:

declare @test int  set @test = 42  GO  select @Test -- causes an error message as @Test is undefined 
like image 25
Guffa Avatar answered Sep 19 '22 18:09

Guffa