views:

107

answers:

4

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 sould I use between that two queries?

Go or ;

+9  A: 

; 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

Faruz
Actually, go is redundant outside "management studio". I wont (-1) though.
Hassan Syed
@Hassan Syed: Yep, you are correct
Faruz
Try executing a statement with `GO` in it through a SqlCommand, it will throw an exception.
ck
Exactly, it's a command to the client tool (SSMS, osql, sqlcmd, etc), not to the server. And in some of these tools, the command can be defined as some other sequence. Though if anyone does this, I implicitly hate them and all the scripts they create. :-|
Damien_The_Unbeliever
yes the go is the command to the intermediate query client tools that manipulate it
HotTester
+3  A: 

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.)

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
Guffa
+2  A: 

GO is not a command to the server, it's the default batch separator for most of the client tools the MS supply. When the client tool encounters "GO" on a new line by itself, it sends whatever commands it has accumulated thus far to the server, and then starts over anew.

What this means is that any variables declared in one batch are not available in subsequent batches. And it also means that multi-line comments can't be placed around a "GO" command - because the server will see the first batch, and see an unterminated comment.

Damien_The_Unbeliever
A: 

It marks the end of a batch in Query Analyzer and therefore signals the end of a stored procedure definition in that batch. As much as i know its not a part of sp. GO isn't a TSQL command.

And ; just ends the statement.

Malcolm