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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

When you think about it, this seems like an easy thing to fix — just make use of the USE statement, but<br />

before we test our new theory, we have to get rid of the old (OK, not that old) database:<br />

USE MASTER;<br />

DROP DATABASE Test;<br />

We can then run our newly modified script:<br />

CREATE DATABASE Test;<br />

USE Test;<br />

CREATE TABLE TestTable<br />

(<br />

col1 int,<br />

col2 int<br />

);<br />

Unfortunately, this has its own problems:<br />

Msg 911, Level 16, State 1, Line 3<br />

Database ‘Test’ does not exist. Make sure that the name is entered correctly.<br />

The parser tries to validate your code and finds that you are referencing a database with your USE command<br />

that doesn’t exist. Ahh, now we see the need for our batches. We need the CREATE DATABASE<br />

statement to be completed before we try to use the new database:<br />

CREATE DATABASE Test;<br />

GO<br />

USE Test;<br />

CREATE TABLE TestTable<br />

(<br />

col1 int,<br />

col2 int<br />

);<br />

Now things work a lot better. Our immediate results look the same:<br />

Command(s) completed successfully.<br />

But when we run our INFORMATION_SCHEMA query, things are confirmed:<br />

TABLE_CATALOG<br />

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

Test<br />

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

Chapter 11: Writing Scripts and Batches<br />

Let’s move on to another example that shows an even more explicit need for precedence.<br />

When you use an ALTER TABLE statement that significantly changes the type of a column or adds columns,<br />

you cannot make use of those changes until the batch that makes the changes has completed.<br />

339

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

Saved successfully!

Ooh no, something went wrong!