Case Statement in SQL Server 2012

Introduction

In this article I described the Case Statement in SQL Server. The Case Statement manipulates the presentation of data without altering the actual data.

First of all we create a table.

Creation of table stu:

create table stu(stuName varchar(15), StuPersantage int)

Insertion of data:


insert
 into stu
select
 'Ram',50 union all
select
 'Ravi',55 union all
select
 'Raj',59 union all
select
 'Rozy',65 union all
select
 'Raman', 70 union all
select
 'Rocky',75 union all
select
 'Ramesh',60 union all
select
 'Rohen',45 union all
select
 'Ravinder',25

Output:

select *  from stu

case-statement-in-sql-serverr.jpg

Case:


The Case Statement is a conditional statement and provides logic like an if/else statement for the SQL Command. With the help of the Case Statement we use when-then-else functionality in SQL Statements. It checks a condition; when the condition is met then one task is done else a different one is done.

Syntax:

Case expression
when expression1 then expression1
when expression2 then expression2
.................................
else expression
end

Example:


select
 stuName, StuPersantage,
'StuStatus'
=case
when
 StuPersantage>=60 then 'first'
when
 StuPersantage>= 50 and StuPersantage< 60 then 'Second'
when
 StuPersantage>=30 and StuPersantage < 50 then 'Third'
else
 'Fail'
end
from
 stu

Output:


case-statement-in-sql-server-2012-.jpg

Summary:


In this article I described the Case Statement in SQL Server. I hope this article has helped you to understand this topic. Please share if you know more about this. Your feedback and constructive contributions are welcome.

Up Next
    Ebook Download
    View all
    Learn
    View all