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.

Chapter 11: Writing Scripts and Batches<br />

358<br />

<strong>Tech</strong>nically speaking, we could do this with nested IF...ELSE statements, but:<br />

❑ It would be much harder to read — especially if the rules were more complex.<br />

❑ We would have to implement the code using a cursor (bad!) and examine each row one at<br />

a time.<br />

In short — yuck!<br />

A CASE statement is going to make this process relatively easy. What’s more, we’re going to be able to<br />

place our condition inline to our query and use it as part of a set operation — this almost always means<br />

that we’re going to get much better performance than we would with a cursor.<br />

Our marketing department has decided they would like to see what things would look like if we<br />

increased prices by 10 percent, so we’ll plug a 10 percent markup into a CASE statement, and, together<br />

with a little extra analysis, we’ll get the numbers we’re looking for:<br />

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

GO<br />

/* I’m setting up some holding variables here. This way, if we get asked<br />

** to run the query again with a slightly different value, we’ll only have<br />

** to change it in one place.<br />

*/<br />

DECLARE @Markup money;<br />

DECLARE @Multiplier money;<br />

SELECT @Markup = .10; -- Change the markup here<br />

SELECT @Multiplier = @Markup + 1; -- We want the end price, not the amount<br />

-- of the increase, so add 1<br />

/* Now execute things for our results. Note that we’re limiting things<br />

** to the top 10 items for brevity -- in reality, we either wouldn’t do this<br />

** at all, or we would have a more complex WHERE clause to limit the<br />

** increase to a particular set of products<br />

*/<br />

SELECT TOP 10 ProductID, Name, ListPrice,<br />

ListPrice * @Multiplier AS “Marked Up Price”, “New Price” =<br />

CASE WHEN FLOOR(ListPrice * @Multiplier + .24)<br />

> FLOOR(ListPrice * @Multiplier)<br />

THEN FLOOR(ListPrice * @Multiplier) + .95<br />

WHEN FLOOR(ListPrice * @Multiplier + .5) ><br />

FLOOR(ListPrice * @Multiplier)<br />

THEN FLOOR(ListPrice * @Multiplier) + .75<br />

ELSE FLOOR(ListPrice * @Multiplier) + .49<br />

END<br />

FROM Production.Product<br />

WHERE ProductID % 10 = 0 -- this is just to help the example<br />

ORDER BY ProductID DESC;<br />

The FLOOR function you see here is a pretty simple one — it takes the value supplied and rounds down<br />

to the nearest integer.

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

Saved successfully!

Ooh no, something went wrong!