laika222
5/1/2017 - 3:14 PM

GO, Batches

-- Batches are sets of commands sent to SQL Server as as unit. Batches determine variable scope, name resolution. To separate batches, use GO. Batches are collections of one or more T-SQL statements sent to SQL Server as a unit for parsing, optimization, and execution and are terminated with the GO clause. Batches are also boundaries for the scope of a variable. Some statements such as CREATE FUNCTION, CREATE PROCEDURE, and CREATE VIEW may not be combined with others in the same batch.

SELECT * FROM Production.Product;
SELECT * FROM Sales.Customer;
GO

-- GO executes all code written since the previous GO. Below, if the entire block is executed, SQL Server will execute a first batch of the two lines above the first GO, and will then execute a second batch of the lines above the second GO, but below the first GO.
USE AdventureWorks;
GO
DECLARE @NmbrContacts int
SELECT @NmbrContacts = COUNT(*)
FROM Person.Contact
PRINT 'The number of contacts as of ' +
      CAST(GETDATE() AS char(20)) + ' is ' +
      CAST(@NmbrContacts AS char (10))
GO

-- GO with a number following it executes the batch a specified number of times.
SELECT * FROM Production.Product;
SELECT * FROM Sales.Customer;
GO 3