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

We also have the CASE statement (aka SELECT CASE, DO CASE, and SWITCH/BREAK in other languages),<br />

but it doesn’t have quite the level of control-of-flow capabilities that you’ve come to expect from other<br />

languages.<br />

The IF … ELSE Statement<br />

350<br />

IF ... ELSE statements work much as they do in any language, although I equate them closest to C in<br />

the way they are implemented. The basic syntax is:<br />

IF <br />

| BEGIN END<br />

[ELSE<br />

| BEGIN END]<br />

The expression can be pretty much any expression that evaluates to a Boolean.<br />

This brings us back to one of the most common traps that I see <strong>SQL</strong> programmers fall into — improper<br />

user of NULLs. I can’t tell you how often I have debugged stored procedures only to find a statement like:<br />

IF @myvar = NULL<br />

Comp: above code is part of note.<br />

This will, of course, never be true on most systems (see below), and will wind up bypassing all their<br />

NULL values. Instead, it needs to read:<br />

IF @myvar IS NULL<br />

The exception to this is dependent on whether you have set the ANSI_NULLS option ON or OFF. The<br />

default is that this is ON, in which case you’ll see the behavior just described. You can change this behavior<br />

by setting ANSI_NULLS to OFF. I strongly recommend against this since it violates the ANSI standard.<br />

(It’s also just plain wrong.)<br />

Note that only the very next statement after the IF will be considered to be conditional (as per the IF).<br />

You can include multiple statements as part of your control-of-flow block using BEGIN...END, but we’ll<br />

discuss that one a little later in the chapter.<br />

To show off a simple version of this, let’s run an example that’s very common to build scripts. Imagine<br />

for a moment that we want to CREATE a table if it’s not there, but to leave it alone if it already exists. We<br />

could make use of the EXISTS operator. (You may recall my complaint that the Books Online calls<br />

EXISTS a keyword when I consider it an operator.)<br />

-- We’ll run a SELECT looking for our table to start with to prove it’s not there<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’;

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

Saved successfully!

Ooh no, something went wrong!