March 02, 2008

Using CASE function to evaluate one or more conditions




As mentioned in the BOL 'CASE Function evaluates a list of conditions and returns one of multiple possible result expressions'. In short CASE function returns a value by evaluating the expression given to it.

Let us see how we can add another column called 'Continent' to the Customers table of the Northwind database. We will be using the CASE function to evaluate the 'Continent' by giving the Country list as the expression.

USE NORTHWIND
SELECT CustomerID, CompanyName,Country, Continent =
CASE
WHEN COUNTRY IN ('Austria','Belgium','Denmark','Finland','France','Germany',
'Ireland','Italy','Norway','Poland','Portugal','Spain','Sweden','Switzerland','UK') THEN 'Europe'
WHEN COUNTRY IN ('Argentina','Brazil','Venezuela') THEN 'SouthAmerica'
WHEN COUNTRY IN ('Canada','Belgium','Mexico','USA') THEN 'NorthAmerica'
ELSE 'UNKNOWN'
END
FROM CUSTOMERS

Once you run this query, you will find that the continent column gets displayed based on the WHEN expression using the CASE function


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

0 Responses to "Using CASE function to evaluate one or more conditions"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions