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

Now, I’ve mixed all sorts of uses of the IF statement there. I have the most basic IF statement — with no<br />

BEGIN...END or ELSE. In my other IF statement, the IF portion uses a BEGIN...END block, but the ELSE<br />

does not.<br />

I did this one this way just to illustrate how you can mix them. That said, I recommend you go back to my<br />

old axiom of “be consistent.” It can be really hard to deal with what statement is being controlled by what<br />

IF...ELSE condition if you are mixing the way you group things. In practice, if I’m using BEGIN...END<br />

on any statement within a given IF, then I use them for every block of code in that IF statement even if<br />

there is only one statement for that particular condition.<br />

The CASE Statement<br />

354<br />

The CASE statement is, in some ways, the equivalent of one of several different statements depending on<br />

the language from which you’re coming. Statements in procedural programming languages that work in<br />

a similar way to CASE include:<br />

❑ Switch: C, C#, C++, Java, php, Perl, Delphi<br />

❑ Select Case: Visual Basic<br />

❑ Do Case: Xbase<br />

❑ Evaluate: COBOL<br />

I’m sure there are others — these are just from the languages that I’ve worked with in some form or<br />

another over the years. The big drawback in using a CASE statement in T-<strong>SQL</strong> is that it is, in many ways,<br />

more of a substitution operator than a control-of-flow statement.<br />

There is more than one way to write a CASE statement — with an input expression or a Boolean expression.<br />

The first option is to use an input expression that will be compared with the value used in each<br />

WHEN clause. The <strong>SQL</strong> <strong>Server</strong> documentation refers to this as a simple CASE:<br />

CASE <br />

WHEN THEN <br />

[...n]<br />

[ELSE ]<br />

END<br />

Option number two is to provide an expression with each WHEN clause that will evaluate to TRUE/FALSE.<br />

The docs refer to this as a searched CASE:<br />

CASE<br />

WHEN THEN <br />

[...n]<br />

[ELSE ]<br />

END<br />

Perhaps what’s nicest about CASE is that you can use it “inline” with (that is, as an integral part of) a<br />

SELECT statement. This can actually be quite powerful.

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

Saved successfully!

Ooh no, something went wrong!