Click here to Skip to main content
Click here to Skip to main content

A Simple Use of SQL CASE Expression

By , 19 Aug 2009
 

Table of Contents

Introduction

This article will give you an idea about how to use CASE expression in T-SQL or as a formula of a particular column.

What is CASE Expression 

CASE is the special scalar expression in SQL language. CASE expression is widely used to facilitate determining / setting a new value from user input values. CASE expression can be used for various purposes which depends on the business logic.

CASE expression is mostly used in SQL stored procedure or as a formula for a particular column, which optimizes the SQL statements.

Syntax of CASE Expression 

SQL CASE expression is used as a type of IF-THEN-ELSE statement. It is similar to switch statement in recent programming languages such as C# and Java. The syntax of the CASE statement is simple as follows:

1.    CASE column_name  
2.      WHEN condition1 THEN result1  
3.      WHEN condition2 THEN result2  
4.      ...  
5.      ELSE result  
6.    END

Sample Example of CASE Statement 

DECLARE @intInput INT
SET @intInput = 2
SELECT CASE(@intInput) WHEN 1 THEN 'One' WHEN 2 THEN 'Two' _
		WHEN 3 THEN 'Three' ELSE 'Your message.' END 

Use of CASE Expression

The case expression can be used anywhere scalar expressions are allowed, including in WHERE and HAVING clauses of the select statement.

In this article, I would like to show the most commonly used case expression in:

  • Stored procedure 
  • Formula of a particular column 
  • View

Basic Use in a Stored Procedure

A simple example of using CASE in a stored procedure is given below:

-- =============================================
-- Author: Md. Marufuzzaman
-- Create date: 
-- Description:    A simple example of CASE expression.
-- =============================================
/*
DECLARE @varCountry VARCHAR(100)
EXEC spGetCountry 1, @varCountry OUTPUT
SELECT @varCountry
*/

ALTER PROCEDURE [dbo].[spGetCountry]
 @intCode        INT
,@varOutPut         VARCHAR(100) OUTPUT
AS
BEGIN
 
SELECT CASE(@intCode) WHEN 1 THEN 'Country_1'
              WHEN 2 THEN 'Country_2'
              WHEN 3 THEN 'Country_3'
              WHEN 4 THEN 'Country_4'
              WHEN 5 THEN 'Country_5'
              WHEN 6 THEN 'Country_6'
              WHEN 7 THEN 'Country_7'
              WHEN 8 THEN 'Country_8'
              WHEN 9 THEN 'Country_9'
              WHEN 10 THEN 'Country_10'         
                      ELSE 'Unknown' END  
      
END

Basic Use in a Table Column Formula

When we create a Table in design mode, SQL server provides us the properties of each column, where we can set various property values like a default value of a column, identity of a column, etc. Every column has a special property that is a custom formula, where you can set your own formula for data manipulation. Let’s take an example:

Our target is to write a formula for a column, and this formula is responsible for setting a new value for another column.

Figure 1 - How we can set a formula for a particular column

A simple example of using CASE in a Table column formula is given below:

// SQL CASE statement
(case [Code] when (1) then 'Country_1' when (2) then 'Country_2' _
	when (3) then 'Country_3' when (4) then 'Country_4' when (5) _
	then 'Country_5' when (6) then 'Country_6' when (7) then 'Country_7' _
	when (8) then 'Country_8' when (9) then 'Country_9' when (10) _
	then 'Country_10' else 'Unknown' end)

When you insert / update a value at column “code”, the SQL server will fire the formula which is associated with the column “code” and finally set the value of that particular column.

Output
Figure 2 - How column "Country" sets value when column code value is inserted / updated

Basic Use in a View

There is nothing new to use CASE expression in a view object. As I mentioned before, CASE expression can be used anywhere scalar expressions are allowed, including in WHERE and HAVING clauses of the select statement.

Conclusion 

I hope that you will get an idea about how to use CASE expression. Enjoy!

History

  • 18th August 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Md. Marufuzzaman
CEO
Bangladesh Bangladesh
He is the founder & CEO of MNH Technologies and working for urban and rural sectors to improve people’s lifestyle, better medical facilities, education, social business etc. He has over ten years of professional experiences in design and developing Client-Server, Multi-Tier, Database, Web based business software solutions, Enterprise Applications, API, WebAPI, Google Analytics implementation, Add-In, Documentation & Technical Writing etc for Windows / Mac using Microsoft SQL Server, Oracle, MySql, PS, C#, VB.NET, ASP.NET, PHP, RoR, Visual Basic etc. He has also more than two years experience in Mobile-VAS (Platform Development).
 
He worked for various software development & technology consulting. His core focus on technologies to create dynamic data-driven systems that add value to your business and dynamic technology consulting that builds advanced solutions for the industries across the various vertices.
 
He also work as a Solution Architect at Dhrupadi Techno Consortium Limited (DTCL) and responsible for analyzing business requirements and offered optimum solutions (multiple options), which would address all current requirements, provide flexibility for future growth and allow smooth transition between old system and new system.
 
He graduated with honors from The University of Asia Pacific, in Computer Science and Engineering. He was awarded as “Most Valuable Professional” (MVP) at 2010 and 2011 by CodeProject.com and also selected as a Mentor of CodeProject.com
 
Specialties: Software Development Management, System Integration, Data Warehouse Architecture, Virtualization.
Follow on   Twitter

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberAndrewOkoth25-Apr-13 21:43 
worked for me, thanks man..!
GeneralMy vote of 5memberTasnia.Maruf20-Sep-10 0:26 
Good work
GeneralRe: My vote of 5mvpMd. Marufuzzaman3-Oct-10 4:13 
Thanks
Thanks
Md. Marufuzzaman


I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.

GeneralMy vote of 1membergrandtree29-Apr-10 16:05 
It's too simple, and the code is not carefully tested, I think.
GeneralCase syntaxmemberMember 150309625-Aug-09 21:27 
Hello,
 
There is another syntax for the case that is sometimes usefull and easier to write than the classic one...
 
Select
...
case when colA > colB then 'Dothis' else 'Dothat' end
...
 
Greetings
GeneralRe: Case syntaxgroupMd. Marufuzzaman26-Aug-09 0:35 
Thanks for your suggestion, Actually SQL CASE expression is used as a type of IF-THEN-ELSE statement.
WHEN (Conditional statement) THEN
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: Case syntaxgroupMd. Marufuzzaman26-Aug-09 0:35 
Thanks for your suggestion, Actually SQL CASE expression is used as a type of IF-THEN-ELSE statement.
WHEN (Conditional statement) THEN
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralRe: Case syntaxgroupMd. Marufuzzaman26-Aug-09 0:49 
One think i forgot that is scalar expressions are allowed...Thumbs Up | :thumbsup: Smile | :)
 
I will not say I have failed 1000 times; I will say that I have discovered 1000 ways that can cause failure – Thomas Edison.


Don't forget to click [Vote] / [Good Answer] on the post(s) that helped you.
 
Thanks
Md. Marufuzzaman

GeneralYou are doing great !mvpAbhijit Jana19-Aug-09 5:36 
You are doing great with Beginners SQL Server Article.
 
Keep it up !Thumbs Up | :thumbsup:
 
Abhijit Jana | Codeproject MVP
Web Site : abhijitjana.net
Don't forget to click "Good Answer" on the post(s) that helped you.

GeneralRe: You are doing great !groupMd. Marufuzzaman19-Aug-09 7:22 
Thanks ABHIJIT........Smile | :)
 

 
Thanks
Md. Marufuzzaman

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 19 Aug 2009
Article Copyright 2009 by Md. Marufuzzaman
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid