Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

Use Case Statement with Select Query in SQL Server | Case Statement Example in SQL Server

Jul 4, 2012
Introduction:

In this article I will explain how to write SQL  query to use case statement with select in SQL Server or case statement example in SQL Server.

Description:

In previous posts I explained Distinct keyword with top statement, Replace function, substring function to get particular part of string and many articles relating to SQL Server. Now I will explain how to write query to use case statement in SQL Server.

Generally case statement is conditional statement that will return column value based on the evaluation of set conditions. We can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.

Declaration of Simple Case statement Syntax:

SELECT
CASE Column1
WHEN Expression1 THEN Value1
WHEN Expression2 THEN Value2
WHEN Expression3 THEN Value3
ELSE Value4
END,
Column2,Column3 From TableName
In above case statement declaration Column1 value will display based on the expression match.

Now I will explain with example I have EmployeeDetails like this

 
Check below query to use Case Statement:


SELECT EmpId,
EmpName=
CASE EmpName
WHEN 'Mahesh' THEN 'Dasari Mahesh'
WHEN 'Prasanthi' THEN 'Donthi Prasanthi'
WHEN 'Madhav' THEN 'Yemineni Madhav'
WHEN 'Nagaraju' THEN 'Dasari Nagaraju'
ELSE ''
END,
Role
FROM Employeedetails
Once if I run above query Output will be like this

 
If we want to use SQL statement with searched case expression that would be like this


SELECT EmpId,
EmpName=
CASE
WHEN EmpName='Mahesh' THEN 'Dasari Mahesh'
WHEN EmpName='Prasanthi' THEN 'Donthi Prasanthi'
WHEN EmpName='Madhav' THEN 'Yemineni Madhav'
WHEN EmpName='Nagaraju' THEN 'Dasari Nagaraju'
ELSE ''
END,
Role
FROM Employeedetails
Output for searched case statement



If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

5 comments :

Unknown said...

u r greate sir

Anonymous said...

thank u..

Anonymous said...

HOW TO USE CASE STATEMENT WHEN THREE TABLES JOINING

Unknown said...

very very thanks sir

Unknown said...

Our Explanation is always very nice very-very simple and helpful

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.