SQL Server: Do I need to use GO statements between batches? - sql

I have seen people use GO statement between batches of SQL code, but AFAICS it is not mandatory (SQL Server 2008). What are the benefits using GO statements between batches/sets of SQL statements?

They're not strictly required - they're just instructions for the SQL Server Management Studio to execute the statements up to this point now and then keep on going. GO is not a T-SQL keyword or anything - it's just an instruction that works in SSMS.
Sometimes, you need a GO - e.g. if you add a column to a table, and then want to select it again, you need to have a GO between the adding of the column, and the query of it.
E.g. if you try to execute this, you'll get errors from SSMS:
ALTER TABLE (sometable) ADD DateTimeStamp DATETIME
SELECT ID, DateTimeStamp FROM (sometable) WHERE ID > 5
Results in:
Msg 207, Level 16, State 1, Line 9
Invalid column name 'datetimestamp'.
The point is: SSMS is trying to verify the whole statement at once, but on the SELECT statement, it will complain about the missing DateTimeStamp column.
ALTER TABLE (sometable) ADD DateTimeStamp DATETIME
GO
SELECT ID, DateTimeStamp FROM (sometable) WHERE ID > 5
If you put a GO between the two statements, it'll work, because SSMS won't parse and verify the whole statement ahead of time - it will do the first part, and then only parse the second (after the GO).
But other than situations like this one, GO is hardly ever required.

It's only mandatory in SQL tools to tell SSMS where the batch start and end is. It's also required for some statements such as CREATE TRIGGER which must the first in the batch
For example, in a c# to SQL Server call it has no meaning

Related

The real function of the "GO" Statement in SQL?

I heard that GO statement separates the command batches in SQL. And the CREATE transaction should be the only query on a batch.
But when i try:
Create database dbTest
Create table tbSomething(ID int primary key,Name varchar(30))
GO
The output is still SUCCESS.
So how does the GO Statement affect the SQL batches?
GO is used to divide a script into multiple batches.
The word GO is not a sql statement. It is understood by the SQL batch processor (for example SSMS) not by SQL Server.
Simply put, if GO appears on a line on its own, SSMS sends each section delimited by GO as a separate batch. SQL Server never sees the GO lines, only the SQL between them.
Because SQL Server has a syntactic rule that stored procedures must be defined in a batch on their own, you will often find database creation scripts which use GO to delimit the batches so that multiple stored procedures can be created from one script. However it is the client software which understands GO and divides the batches, not SQL server.
'GO' statement in SQL server is to just sends a signal to take the current batch of SQL statements for execution.
To tell in simple words, it works like a delimiter.
It is an indication of end of SQL statement [i.e., 1 batch that needs to be executed].

SQL Server Add Column then Update Column Error

I'm writing a sql script that modifies multiple tables after importing them. In one table I don't have a 'RCVDDATE' column but I do in another related table. I'm adding the new table with this command:
ALTER TABLE TEST.CASES.ADDRESS
ADD RCVDDATE DATE;
And then I'm running this command to bring in the correct values:
UPDATE TEST.CASES.ADDRESS
SET RCVDDATE = c.RCVDDATE
FROM TEST.CASES.CALLS c
Where TEST.CASES.ADDRESS.CALL_NUMBER = c.CALL_NUMBER;
Individually they work fine. But when I execute them in a script it throws an error:
Msg 207, Level 16, State 1, Line 5
Invalid column name 'RCVDDATE'.
Am I having a problem with Intellisense or is it something else? If you have any suggestions on how I can get the script to run in SQL Server, please advise.
You need a GO statement to separate your batches. From https://learn.microsoft.com/en-us/sql/t-sql/language-elements/sql-server-utilities-statements-go?view=sql-server-2017
SQL Server applications can send multiple Transact-SQL statements to an instance of SQL Server for execution as a batch. The statements in the batch are then compiled into a single execution plan. Programmers executing ad hoc statements in the SQL Server utilities, or building scripts of Transact-SQL statements to run through the SQL Server utilities, use GO to signal the end of a batch.

Do I have to write the "GO" word in order to execute an SQL server statement?

I have little to no experience with TSQL and SQL Server - so in MySQL when I want to execute a statement I simply write:
Select * from users
...and then hit ENTER.
However now I see many SQL Server tutorials that you have the GO word immediately after each statement. Do I have to write this? For example:
Select * from users; GO
Or I can simply write:
Select * from users; <enter key pressed...>
In SQL Server, go separates query batches. It's optional in most situations.
In earlier versions of SQL Server, you had to do a go after altering a table, like:
alter table MyTable add MyColumn int
go
select MyColumn from MyTable
If you didn't, SQL Server would parse the query batch, and complain that MyColumn didn't exist. See MSDN:
SQL Server utilities interpret GO as a
signal that they should send the
current batch of Transact-SQL
statements to an instance of SQL
Server. The current batch of
statements is composed of all
statements entered since the last GO,
or since the start of the ad hoc
session or script if this is the first
GO.
GO separates batches, as Andomar wrote.
Some SQL statements (e.g. CREATE SCHEMA) need to be the first or only statements within a batch. For example, MSDN states
The CREATE PROCEDURE statement cannot
be combined with other Transact-SQL
statements in a single batch.
Local variables are also limited to a batch, and therefore are not accessible after a GO.
Go is optional, no need to write that in your sql statements.
You don't have to. What the GO will do is execute each statement (at least in Sql Server)
As the other answerers said before me, you don't really NEED Go.
There is only one case when you have to use it, and that's when you want to create a table or view and then select from it.
For example:
create view MyView as select * from MyTable
go
select * from MyView
Without Go, Sql Server won't execute this because the select statement is not valid, because the view doesn't exist at that moment.

Executing a command string with GO at the end

I need to execute a command string with using GO command at the end like
exec('SELECT * FROM tblTmp where Id = 1 GO')
After executing I have
Incorrect syntax near 'GO'.
If I execute exec('SELECT * FROM tblTmp GO') everything is OK
What's the issue here?
Thank you.
GO is not an SQL command, it is a batch separator understood by clients like osql, sqlcmd, and SSMS but not the engine itself.
If you write something like this in SSMS:
SELECT 1
GO
SELECT 2
GO
, the engine sends two batches with one statement in each instead of one batch with two statements.
In your second query, GO is treated as an alias to the table tblTmp.
Just remove GO from your query.
You do not need to use GO for a single SQL statement. Only when you're batching several statements into a single script do you need to use a separator. Also, if you're executing these programmatically you should be using the semicolon (;) statement terminator instead of GO to separate your SQL statement.
Here's a handy SQL Server Central article on the usage of GO and the semicolon.

What is the difference between ";" and "GO" in T-SQL?

I use ADO.NET as well as the sqlcmd utility to send SQL scripts to SQL Server 2008. What is the difference between using ; and GO to separate chunks of 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.
You cannot put a GO into a string of SQL and send it as part of a ADO.NET command object as SQL itself does not understand the term. Another way to demonstrate this is with the profiler: set up some statements that use GO in Query Analyzer/Management Studio and then run the profiler when you execute. You will see they are issued as separate commands to the server.
The semi-colon is used to signify the end of a statement itself, not necessarily a whole batch.
http://msdn.microsoft.com/en-us/library/ms188037.aspx
"GO" is similar to ; in many cases, but does in fact signify the end of a batch.
Each batch is committed when the "GO" statement is called, so if you have:
SELECT * FROM table-that-does-not-exist;
SELECT * FROM good-table;
in your batch, then the good-table select will never get called because the first select will cause an error.
If you instead had:
SELECT * FROM table-that-does-not-exist
GO
SELECT * FROM good-table
GO
The first select statement still causes an error, but since the second statement is in its own batch, it will still execute.
GO has nothing to do with committing a transaction.
semicolon is a statement separator. The previous statement(s) is not necessarily executed when a semicolon is encountered.
GO
Signifies the end of a batch. Executes the previous batch of statements, as does encountering the end of the block.
GO 2
Means execute the batch that many times. I think I've used that option maybe twice in my life. Then again, I'm not a DBA by trade.
Under SQL Server TSQL (2005 - 2016) bear in mind that:
Semicolon (;) is a block terminator.
GO is a batch terminator.
Additionally, GO can be used to invoke the same DML block multiple times using the following syntax:
GO [count]
Where [count] is a positive integer that indicates how many times the TSQL block of commands preceding said GO are to be carried out over and over.
Also, unlike semicolon, GO is mandatory before a new DDL, say, when you create a new view, since a semicolon separating previous commands will trigger an error. For example:
drop view #temporary_viewGO
create view #another_view...
--> NO ERRORS
If you replaced GO with a semicolon in the previous example, it will raise the following error message:
'CREATE VIEW' must be the first statement in a query batch.
'GO' is typically used to indicate the end of a batch of SQL statements which means that you could have a begin transaction and end transaction wrapped up into a single collection of statements that could fail or succeed together.
';' is generally used to separate multiple SQL statements from one another. This is noticable in SQL scripts that need to return multiple recordsets, such as `select * from table1; select * from table2;' which would result in two separate recordsets on the client's side.
The command GO means the end of a batch.
Therefore all variables declared before GO are invalid after the GO command.
Against the semicolon does not end the batch.
If You will use a DML command in a procedure, use the semicolon instead GO.
For example:
CREATE PROCEDURE SpMyProc
#myProcParam VARCHAR(20)
AS
DECLARE #myOtherParam INT = 5
;DISABLE TRIGGER ALL ON tMyTable
UPDATE tMyTable SET myVar = #myProcParam, mySecondVar = #myOtherParam
;ENABLE TRIGGER OLL ON tMyTable
I thought the ; character separates a list of SQL commands, GO just instructs SQL Server to commit all the previous commands.