17.06.2013 Views

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

Beginning Microsoft SQL Server 2008 ... - S3 Tech Training

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

11<br />

Writing Scripts and Batches<br />

Whether you’ve realized it or not, you’ve already been writing <strong>SQL</strong> scripts. Every CREATE statement<br />

that you write, every ALTER, every SELECT is all (if you’re running a single statement) or<br />

part (multiple statements) of a script. It’s hard to get excited, however, over a script with one line<br />

in it — could you imagine Hamlet’s “To be, or not to be …” if it had never had the lines that<br />

follow — you wouldn’t have any context for what he was talking about.<br />

<strong>SQL</strong> scripts are much the same way. Things get quite a bit more interesting when you string several<br />

commands together into a longer script — a full play or at least an act to finish our Shakespeare<br />

analogy. Now imagine that we add a richer set of language elements from .NET to the equation —<br />

now we’re ready to write an epic!<br />

Scripts generally have a unified goal. That is, all the commands that are in a script are usually<br />

building up to one overall purpose. Examples include scripts to build a database (these might be<br />

used for a system installation), scripts for system maintenance (backups, Database Consistency<br />

Checker utilities (DBCCs), index defragmentation, and more) — scripts for anything where several<br />

commands are usually run together.<br />

We will be looking into scripts during this chapter and adding in the notion of batches — which<br />

control how <strong>SQL</strong> <strong>Server</strong> groups your commands together. In addition, we will take a look at<br />

sqlcmd — the command-line utility, and how it relates to scripts.<br />

sqlcmd was first added in <strong>SQL</strong> <strong>Server</strong> 2005. For backward compatibility only, <strong>SQL</strong> <strong>Server</strong> continues<br />

to support osql.exe (the previous tool that did command line work). You may also see references<br />

to isql.exe (do not confuse this with isqlw.exe), which served this same function in earlier<br />

releases. isql.exe is no longer supported.<br />

Script Basics<br />

A script technically isn’t a script until you store it in a file where it can be pulled up and reused.<br />

<strong>SQL</strong> scripts are stored as text files. The <strong>SQL</strong> <strong>Server</strong> Management Studio provides many tools to<br />

help you with your script writing. The basic query window is color coded to help you not only

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!