Compartilhar via


Batch Examples

These examples are scripts that use Microsoft SQL Server Management Studio Code editor and the sqlcmd utility GO command to define batch boundaries.

The following example creates a view. Because CREATE VIEW must be the only statement in a batch, the GO commands are required to isolate the CREATE VIEW statement from the USE and SELECT statements around it.

USE AdventureWorks;
GO 
CREATE VIEW dbo.vProduct
AS
SELECT ProductNumber, Name
FROM Production.Product;
GO 
SELECT * 
FROM dbo.vProduct;
GO 

The following example shows several batches combined into one transaction. The BEGIN TRANSACTION and COMMIT statements delimit the transaction boundaries. The BEGIN TRANSACTION, USE, CREATE TABLE, SELECT, and COMMIT statements are all in their own single-statement batches. All of the INSERT statements are included in one batch.

BEGIN TRANSACTION
GO
USE AdventureWorks;
GO
CREATE TABLE dbo.mycompanies
(
 id_num int IDENTITY(100, 5),
 company_name nvarchar(100)
)
GO
INSERT mycompanies (company_name)
   VALUES (N'A Bike Store');
INSERT mycompanies (company_name)
   VALUES (N'Progressive Sports');
INSERT mycompanies (company_name)
   VALUES (N'Modular Cycle Systems');
INSERT mycompanies (company_name)
   VALUES (N'Advanced Bike Components');
INSERT mycompanies (company_name)
   VALUES (N'Metropolitan Sports Supply');
INSERT mycompanies (company_name)
   VALUES (N'Aerobic Exercise Company');
INSERT mycompanies (company_name)
   VALUES (N'Associated Bikes');
INSERT mycompanies (company_name)
   VALUES (N'Exemplary Cycles');
GO

SELECT id_num, company_name
FROM dbo.mycompanies
ORDER BY company_name ASC;
GO
COMMIT;
GO

The following script illustrates two problems. First, the variable @MyVar is declared in the second batch and referenced in the third. Also, the second batch has the start of a comment, but no end. The third batch has the end of the comment, but when sqlcmd reads the GO command it sends the first batch to Microsoft SQL Server 2005 where the /* with no matching */ generates a syntax error.

USE AdventureWorks;
GO
DECLARE @MyVar INT
/* Start of the split comment.
GO
End of the split comment. */
SELECT @MyVar = 29;
GO