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.

Chapter 11: Writing Scripts and Batches<br />

To expand our earlier example just a bit, let’s actually print a warning message out if we do not create<br />

our table:<br />

-- Now we’re run our conditional CREATE statement<br />

IF NOT EXISTS (<br />

SELECT s.name AS SchemaName, t.name AS TableName<br />

FROM sys.schemas s<br />

JOIN sys.tables t<br />

ON s.schema_id = t.schema_id<br />

WHERE s.name = ‘dbo’<br />

AND t.name = ‘OurIFTest’<br />

)<br />

CREATE TABLE OurIFTest(<br />

Col1 int PRIMARY KEY<br />

);<br />

ELSE<br />

PRINT ‘WARNING: Skipping CREATE as table already exists’;<br />

If you have already run the preceding example, then the table will already exist, and running this second<br />

example should get you the warning message:<br />

WARNING: Skipping CREATE as table already exists<br />

Grouping Code into Blocks<br />

352<br />

Sometimes you need to treat a group of statements as though they were all one statement (if you execute<br />

one, then you execute them all — otherwise, you don’t execute any of them). For instance, the IF statement<br />

will, by default, consider only the very next statement after the IF to be part of the conditional code.<br />

What if you want the condition to require several statements to run? Life would be pretty miserable if you<br />

had to create a separate IF statement for each line of code you wanted to run if the condition holds.<br />

Thankfully, like most any language with an IF statement, <strong>SQL</strong> <strong>Server</strong> gives us a way to group code into<br />

blocks that are considered to all belong together. The block is started when you issue a BEGIN statement<br />

and continues until you issue an END statement. It works like this:<br />

IF <br />

BEGIN --First block of code starts here -- executes only if<br />

--expression is TRUE<br />

Statement that executes if expression is TRUE<br />

Additional statements<br />

...<br />

...<br />

Still going with statements from TRUE expression<br />

IF --Only executes if this block is active<br />

BEGIN<br />

Statement that executes if both outside and inside<br />

expressions are TRUE<br />

Additional statements<br />

...<br />

...<br />

Still statements from both TRUE expressions<br />

END

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

Saved successfully!

Ooh no, something went wrong!