Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using GO keyword in SQL Server

i know the use of GO keyword. it sends multiple statements to sql server as a whole group, instead of sending each statement one by one. i hope i am right!

but i want to know that do programmers use it in real applications. like if we create a stored procedure, then that also does the same thing,it also compiles the code and make an execution plan , and send the whole group to the server.

so do we need to specify the GO keyword in the coding of database objects such as triggers, views, stored procedures ?

like image 852
sqlchild Avatar asked Mar 04 '11 06:03

sqlchild


People also ask

Do I need to use go in SQL?

In the command line, you need to use GO because that way, you know that the T-SQL statement ended and you know that you can execute it. For example, this T-SQL query will show the databases. The query requires a GO at the end to inform to sqlcmd that it is the end of the batch.

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.

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.


1 Answers

GO is a command used for signaling the end of a batch. Note that it is not a T-SQL statement.

Batch is a group of one or more Transact-SQL statements sent at the same time from an application to SQL Server for execution

GO is very useful in SQL Server. Though, you need to use it only when is really needed. So, you need to keep in mind that along with defining a batch using the GO command, you define the scope of that specific piece of T-SQL code. The local variables defined in a batch are specific to that batch.

Scope example -

DECLARE @STRING1 AS VARCHAR(50)
DECLARE @STRING2 AS VARCHAR(50)

SET @STRING1='BATCH 2'
SET @STRING2='BATCH 3'

SELECT @STRING1 AS RESULT
GO

SELECT @STRING2 AS RESULT
GO

Running this will give you error saying @STRING2 is not declared. Because the scope of that variable ends with the GO. So beware of using GO and use smartly.

Source - http://aartemiou.blogspot.com/2009/08/using-go-command-in-sql-server.html

like image 199
Sachin Shanbhag Avatar answered Oct 18 '22 20:10

Sachin Shanbhag