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.

-- 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 />

-- And now look again to prove that it’s been created.<br />

SELECT ‘Found Table ‘ + s.name + ‘.’ + t.name<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 />

The meat of this is in the middle — notice that our CREATE TABLE statement runs only if no matching table<br />

already exists. The first check we did on it (right at the beginning of the script) found the table didn’t exist,<br />

so we know that the IF is going to be true and our CREATE TABLE will execute.<br />

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

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

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

Table dbo.OurIFTest<br />

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

The ELSE Clause<br />

Chapter 11: Writing Scripts and Batches<br />

Now this thing about being able to run statements conditionally is just great, but it doesn’t really deal<br />

with all the scenarios we might want to deal with. Quite often — indeed, most of the time — when we<br />

deal with an IF condition, we have specific statements we want to execute not just for the true condition,<br />

but also a separate set of statements that we want to run if the condition is false — or the ELSE<br />

condition.<br />

You will run into situations where a Boolean cannot be evaluated — that is, the<br />

result is unknown (for example, if you are comparing to a NULL). Any expression<br />

that returns a result that would be considered as an unknown result will be treated<br />

as FALSE.<br />

The ELSE statement works pretty much as it does in any other language. The exact syntax may vary<br />

slightly, but the nuts and bolts are still the same; the statements in the ELSE clause are executed if the<br />

statements in the IF clause are not.<br />

351

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

Saved successfully!

Ooh no, something went wrong!