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.

Chapter 11: Writing Scripts and Batches<br />

Using Batches to Establish Precedence<br />

338<br />

Note that, if you DROP an object, you may want to place the DROP in its own batch or at<br />

least with a batch of other DROP statements. Why? Well, if you’re going to later create an<br />

object with the same name, the CREATE will fail during the parsing of your batch unless<br />

the DROP has already happened. That means you need to run the DROP in a separate and<br />

prior batch so it will be complete when the batch with the CREATE statement executes.<br />

Perhaps the most likely scenario for using batches is when precedence is required — that is, you need<br />

one task to be completely done before the next task starts. Most of the time, <strong>SQL</strong> <strong>Server</strong> deals with this<br />

kind of situation just fine — the first statement in the script is the first executed, and the second statement<br />

in the script can rely on the server being in the proper state when the second statement runs. There are<br />

times, however, when <strong>SQL</strong> <strong>Server</strong> can’t resolve this kind of issue.<br />

Let’s take the example of creating a database together with some tables:<br />

USE master;<br />

CREATE DATABASE Test;<br />

CREATE TABLE TestTable<br />

(<br />

col1 int,<br />

col2 int<br />

);<br />

Execute this and, at first, it appears that everything has gone well:<br />

Command(s) completed successfully.<br />

However, things are not as they seem — check out the INFORMATION_SCHEMA in the Test database:<br />

USE Test;<br />

SELECT TABLE_CATALOG<br />

FROM INFORMATION_SCHEMA.TABLES<br />

WHERE TABLE_NAME = ‘TestTable’;<br />

And you'll notice something is missing:<br />

TABLE_CATALOG<br />

--------------------<br />

AdventureWorks<strong>2008</strong><br />

(1 row(s) affected)<br />

Hey! Why was the table created in the wrong database? The answer lies in what database was current<br />

when we ran the CREATE TABLE statement. In my case, it happened to be the master database, so that’s<br />

where my table was created.<br />

Note that you may have been somewhere other than the master database when you ran this, so you may<br />

get a different result. That’s kind of the point though — you could be in pretty much any database.<br />

That’s why making use of the USE statement is so important.

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

Saved successfully!

Ooh no, something went wrong!