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

No comments:

Post a Comment