Batch Examples

These examples are scripts that use SQL Server Query Analyzer and the osql utility GO command to define batch boundaries.

This 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 pubs

GO /* Signals the end of the batch */

  

CREATE VIEW auth_titles

AS

SELECT *

FROM authors

GO /* Signals the end of the batch */

  

SELECT *

FROM auth_titles

GO /* Signals the end of the batch */

  

This example show 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 pubs

GO

CREATE TABLE mycompanies

(

 id_num int IDENTITY(100, 5),

 company_name nvarchar(100)

)

GO

INSERT mycompanies (company_name)

    VALUES ('New Moon Books')

INSERT mycompanies (company_name)

    VALUES ('Binnet & Hardley')

INSERT mycompanies (company_name)

    VALUES ('Algodata Infosystems')

INSERT mycompanies (company_name)

    VALUES ('Five Lakes Publishing')

INSERT mycompanies (company_name)

    VALUES ('Ramona Publishers')

INSERT mycompanies (company_name)

    VALUES ('GGG&G')

INSERT mycompanies (company_name)

    VALUES ('Scootney Books')

INSERT mycompanies (company_name)

    VALUES ('Lucerne Publishing')

GO

SELECT *

FROM 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 osql reads the GO command it sends the first batch to Microsoft® SQL Server™ where the /* with no matching */ generates a syntax error.

USE Northwind

GO
DECLARE @MyVar INT

/* Start of the split comment.

GO

End of the split comment. */

SELECT @MyVar = 29

GO

  


(c) 1988-98 Microsoft Corporation. All Rights Reserved.