Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...>
like image 281
leo Avatar asked Mar 27 '11 16:03

leo


2 Answers

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.

like image 102
Andomar Avatar answered Oct 06 '22 20:10

Andomar


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.

like image 26
devio Avatar answered Oct 06 '22 20:10

devio