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.
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. |
|||
|
|||
5 comments :
u r greate sir
thank u..
HOW TO USE CASE STATEMENT WHEN THREE TABLES JOINING
very very thanks sir
Our Explanation is always very nice very-very simple and helpful
Note: Only a member of this blog may post a comment.