AlphaPress Publishing
P.O. Box 5942 Albany, NY 12205
Tel: 518-250-3890
Email: alphapress@hotmail.com  


  
Click to buy this book from Amazon

Section Menu 

News

Pindaro is now working on a comprehensive book on SQL Server 2014.  For any comments you can email the author at alphapress@hotmail.com.

  

 

 

Update records conditionally using the switch function

To contact the author click here

This article is from the book "Access 2007 Pure SQL

To download the sample database click here


Update conditionally using the switch() function

Update product prices using different update conditions for every supplier

Discussion:

I know that in everyday work scenarios, our suppliers, customers, students, or partners do not set up meetings to send us uniform and standardized information just so that we can have a nice time with our operations.  Most probably, they send us their own percentage increases and not at the same time.  So, what can we do to take care of this business fact in minutes instead of making it an operational and administrative nightmare?  We can combine the powers of the update statement and the switch() function.  As you can see below, our suppliers sent us percentage updates ranging from 2% all the way up to 15%.  Using the update statement with the switch() function, we obtain the following:  First, using just one statement, we can take care of all of the particular updates in minutes.  Second, the statement is so clean that it is reusable the next time we need to do the same job.  Third, suppose that some of our suppliers have not sent us any updates.  We can leave the statement below as is and update the ProductUnitPrice with itself as is the case with supplierID=5 where nothing is updated. 

Code:

update Qry_SupplierPrices

SET ProductUnitPrice =

SWITCH (

supplierid=1,      ProductUnitPrice*(1.1) ,

supplierid=2,      ProductUnitPrice*(1.05),

supplierid=3,      ProductUnitPrice*(1.1) ,

supplierid=4,      ProductUnitPrice*(1.05) ,

supplierid=5,      ProductUnitPrice ,

supplierid=6,      ProductUnitPrice*(1.02) ,

supplierid=7,      ProductUnitPrice *(1.03),

supplierid=8,      ProductUnitPrice*(1.05) ,

supplierid=9,      ProductUnitPrice*(1.15) ,

supplierid=10,    ProductUnitPrice*(1.1) ,

)

 

Result: