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
About The Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and a new one recently at
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.
Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook
No comments:
Post a Comment