Chapter 11

Writing Scripts and Batches

WHAT YOU WILL LEARN IN THIS CHAPTER:

  • How to combine T-SQL statements into scripts and batches
  • Scope of variables and IDENTITY values
  • Error handling in scripts
  • How to run a batch from the command line
  • How to build and run dynamic SQL statements
  • T-SQL control of flow statements

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 the Shakespeare analogy. Now imagine adding a richer set of language elements from .NET to the equation — now you’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 ...

Get Beginning Microsoft® SQL Server® 2012 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.