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?
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.
You can use the GO command to separate batches of SQL commands in database scripts. The GO command executes all the SQL statements in the current batch. A batch is defined as all the SQL commands since the previous GO command, or since the start of the script if this is the first GO command in the script.
Go is optional, no need to write that in your sql statements. Show activity on this post. Show activity on this post.
Semicolon after SQL Statements? Some database systems require a semicolon at the end of each SQL statement. Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With