Pages

Sunday, March 9, 2008

CASE in SQL Server

One of the keys to database performance if keeping your transactions as short as possible.we will look at a couple of tricks using the CASE statement to perform multiple updates on a table in a single operation.

This example uses the pubs database to adjust book prices for a sale by different amounts according to different criteria. In the example I am going to knock 25% off all business books from any publisher, and 10% off any non-business books from a particular publisher. You might be tempted to wrap two separate update statements into one transaction like this:

begin tran
update titles set ...
update titles set ...
commit tran

The down side of this technique is that it will read through the table twice, once for each update. If we code our update like the example below, then the table will only need to be read once. For large tables, this can save us a lot of disk IO, especially if the query requires a table scan over a long table

update titles
set price =
case
when type = "business"
then price * 0.75
when pub_id = "0736"
then price * 0.9
end
where pub_id = "0736" OR
type = "business"


Note that there is a definite "top-down" priority involved in the CASE statement. For business books from publisher 0736 the "business" discount will apply because this is the first condition in the list to be fulfilled. However, we will not give a further 10% publisher discount, even though the criteria for the second "when" clause is satisfied, because the CASE statement only evaluates criteria until it finds the first one that fits.

1 comment: