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.

A Simple CASE<br />

A simple CASE takes an expression that equates to a Boolean result. Let’s get right to an example:<br />

Use AdventureWorks<strong>2008</strong>;<br />

GO<br />

SELECT TOP 10 SalesOrderID,<br />

SalesOrderID % 10 AS ‘Last Digit’,<br />

Position = CASE SalesOrderID % 10<br />

WHEN 1 THEN ‘First’<br />

WHEN 2 THEN ‘Second’<br />

WHEN 3 THEN ‘Third’<br />

WHEN 4 THEN ‘Fourth’<br />

ELSE ‘Something Else’<br />

END<br />

FROM Sales.SalesOrderHeader;<br />

For those of you who aren’t familiar with it, the % operator is for a modulus. A modulus works in a similar<br />

manner to the divide by (/), but it gives you only the remainder — therefore, 16 % 4 = 0 (4 goes into 16<br />

evenly), but 16 % 5 = 1 (16 divided by 5 has a remainder of 1). In the example, since we’re dividing by<br />

10, using the modulus is giving us the last digit of the number we’re evaluating.<br />

Let’s see what we got with this:<br />

SalesOrderID Last Digit Position<br />

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

43793 3 Third<br />

51522 2 Second<br />

57418 8 Something Else<br />

43767 7 Something Else<br />

51493 3 Third<br />

72773 3 Third<br />

43736 6 Something Else<br />

51238 8 Something Else<br />

53237 7 Something Else<br />

43701 1 First<br />

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

Notice that whenever there is a matching value in the list, the THEN clause is invoked. Since we have an<br />

ELSE clause, any value that doesn’t match one of the previous values will be assigned whatever we’ve<br />

put in our ELSE. If we had left the ELSE out, then any such value would be given a NULL.<br />

Let’s go with one more example that expands on what we can use as an expression. This time, we’ll use<br />

another column from our query:<br />

USE AdventureWorks<strong>2008</strong>;<br />

GO<br />

SELECT TOP 10 SalesOrderID % 10 AS ‘OrderLastDigit’,<br />

ProductID % 10 AS ‘ProductLastDigit’,<br />

“How Close?” = CASE SalesOrderID % 10<br />

WHEN ProductID % 1 THEN ‘Exact Match!’<br />

WHEN ProductID % 1 - 1 THEN ‘Within 1’<br />

WHEN ProductID % 1 + 1 THEN ‘Within 1’<br />

Chapter 11: Writing Scripts and Batches<br />

355

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

Saved successfully!

Ooh no, something went wrong!