Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

391


Chapter 16: Programming with T-SQL


16


Result:

Beginning execution loop
I'm a batch.
I'm a batch.
I'm a batch.
I'm a batch.
I'm a batch.
Batch execution completed 5 times.

Terminating a batch kills all local variables, temporary tables, and cursors created by that
batch.

DDL Commands
Some T-SQL DDL commands, such as CREATE PROCEDURE, are required to be the only com-
mand in the batch. Long scripts that create several objects often include numerous GO
batch terminators. Because SQL Server evaluates syntax by the batch, using GO throughout
a long script also helps locate syntax errors.

Switching Databases
Interactively, the current database is indicated in the Query Editor toolbar and can be
changed there. In code, the current database is selected with the USE command. You can
insert USE within a batch to specify the database from that point on:

USE AdventureWorks2012;

It’s a good practice to explicitly specify the correct database with the USE command, rather
than assume that the user will select the correct database prior to running the script.

Executing Batches
A batch can be executed in several ways:

■ A complete SQL script (including all the batches in the script) may be executed by
opening the .sql fi le with SQL Server Management Studio’s SQL Editor and press-
ing F5, clicking the! Execute toolbar button, or selecting Query ➪ Execute.

■ (^) Selected T-SQL statements may be executed within SQL Server Management Studio’s
SQL Editor by highlighting those statements and pressing F5, clicking the! Execute
toolbar button, or selecting Query ➪ Execute.
■ An application can submit a T-SQL batch using ADO or ODBC for execution.
■ (^) A SQL script may be executed by running the SQLCMD command-line utility and
passing the SQL script fi le as a parameter.
A SQL script may be executed through PowerShell. Please refer to Chapter 30, “Confi guring and
Managing SQL Server with PowerShell,” for more information.
c16.indd 391c16.indd 391 7/30/2012 5:38:04 PM7/30/2012 5:38:04 PM
http://www.it-ebooks.info

Free download pdf