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

ELSE ‘More Than One Apart’<br />

END<br />

FROM Sales.SalesOrderDetail<br />

ORDER BY SalesOrderID DESC;<br />

Notice that we’ve used equations at every step of the way on this one, yet it still works. . . .<br />

OrderLastDigit ProductLastDigit How Close?<br />

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

3 2 More Than One Apart<br />

3 9 More Than One Apart<br />

3 8 More Than One Apart<br />

2 2 More Than One Apart<br />

2 8 More Than One Apart<br />

1 7 Within 1<br />

1 0 Within 1<br />

1 1 Within 1<br />

0 2 Exact Match!<br />

0 4 Exact Match!<br />

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

As long as the expression evaluates to a specific value that is of compatible type to the input expression,<br />

it can be analyzed, and the proper THEN clause applied.<br />

A Searched CASE<br />

356<br />

This one works pretty much the same as a simple CASE, with only two slight twists:<br />

❑ There is no input expression (remember that’s the part between the CASE and the first WHEN).<br />

❑ The WHEN expression must evaluate to a Boolean value (whereas in the simple CASE examples<br />

we’ve just looked at, we used values such as 1, 3, and ProductID + 1).<br />

Perhaps what I find the coolest about this kind of CASE is that we can completely change around what is<br />

forming the basis of our expression — mixing and matching column expressions, depending on our different<br />

possible situations.<br />

As usual, I find the best way to get across how this works is via an example:<br />

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

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

“How Close?” = CASE<br />

WHEN (SalesOrderID % 10) < 3 THEN ‘Ends With Less Than Three’<br />

WHEN ProductID = 6 THEN ‘ProductID is 6’<br />

WHEN ABS(SalesOrderID % 10 - ProductID)

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

Saved successfully!

Ooh no, something went wrong!