Chapter 11. Writing Scripts and Batches

Whether you've realized it or not, you've already been writing SQL scripts. Every CREATE statement that you write, every ALTER, every SELECT is all (if you're running a single statement) or part (multiple statements) of a script. It's hard to get excited, however, over a script with one line in it—could you imagine Hamlet's "To be, or not to be ..." if it had never had the lines that follow—you wouldn't have any context for what he was talking about.

SQL scripts are much the same way. Things get quite a bit more interesting when you string several commands together into a longer script—a full play or at least an act to finish our Shakespeare analogy. Now imagine that we add a richer set of language elements from .NET to the equation—now we're ready to write an epic!

Scripts generally have a unified goal. That is, all the commands that are in a script are usually building up to one overall purpose. Examples include scripts to build a database (these might be used for a system installation), scripts for system maintenance (backups, Database Consistency Checker utilities (DBCCs), index defragmentation, and more)—scripts for anything where several commands are usually run together.

We will be looking into scripts during this chapter and adding in the notion of batches—which control how SQL Server groups your commands together. In addition, we will take a look at sqlcmd—the command-line utility, and how it relates to scripts.

sqlcmd was first added ...

Get Beginning Microsoft® SQL Server® 2008 Programming now with O’Reilly online learning.

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