IV.1.4. Creating a Script

A T-SQL script is nothing more than several T-SQL statements strung together in a single file or window. Generally, when people refer to scripts, they're talking about files that can be saved and retrieved, but technically what you've been entering throughout this chapter are also referred to as scripts.

Scripts are saved as files for archive purposes. You might have a database and a need to document all its details. By creating a script of the database creation, you can view the options from the script and, if necessary, rebuild the database.

Within a script are batches. Batches are snippets of code that are run together. Often, a script will have many batches. Only one batch can run at a time, and the next batch can't start until the previous batch has finished. T-SQL uses the GO keyword to signify the end of a batch.

For example, the following code shows a partial script separated into two batches:

USE Practice
CREATE Table Employee
. . .

The CREATE DATABASE statement is the only statement in the first batch. The USE statement starts the second batch after the GO statement.

Separating the batches this way allows one batch to complete before another batch begins.

Without the GO statement, the system would try to create a table in the Practice database before the Practice database was created. It wouldn't work; instead, it would result in an error.

IV.1.4.1. Creating a script to create a database

Imagine that you have a database ...

Get Microsoft® SQL Server™ 2008 All-In-One Desk Reference For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.