SIGN UP MEMBER LOGIN:
   
ARTICLE

How to use case statement in SQL Server

Posted by Rohatash Articles | SQL Server October 20, 2010
This article shows the CASE statement in the Transact SQL Server.
Reader Level:

This article shows the CASE statement in the Transact SQL Server.

CASE Statement: SQL Server provides a mechanism for returning different values in a SELECT clause based on Boolean conditions: the CASE statement.

Simple CASE Statement:  The general syntax of the Simple CASE expression.

CASE expression_1

{WHEN expression_2 THEN result_1}...

[else result_n]

END

Simple CASE Expression looks for the first expression in the list of all when clause that match expression_1 and evaluate the corresponding when clause. If there is no match ,then else clause is evaluates.

Searched CASE statement: The syntax of the search CASE statement.

CASE

   {WHEN condition_1 THEN result_1}...

      [else result_n]

END

For example:

Creating a table:

create table student(stu_id int,stu_name varchar(20),marks int);

Inserting the values:

Insert into student values('101','ravi','65');

Insert into student values('102','sumit','32');

Insert into student values('103','rekha','76');

 

Using the select statement:

 

select * from student;

 

OUTPUT:


case-1.gif


In the above table students Id, Name and their marks are given now I want the following output with the help Of CASE statement:

Stu_Id    Stu_Name      Marks        Remarks        Grade
101          Ravi                65          Pass           A
102          Sumit              32          Fail             E 
103          Rekha              76          Pass           A +

 

Using CASE Expression:

 

Select Stu_Id,Stu_Name,Marks,

Case When Marks > 32 Then 'Pass' Else 'Fail'

End as Remarks,

Case When Marks >= 76 Then 'A+'   

         When Marks >= 65 Then 'A'

         When Marks < 35 Then 'E' 

End as Grade

From Student

OUTPUT:

case-2.gif

Login to add your contents and source code to this article
This Feature is Sponsored By
post comment
COMMENT USING
TRENDING UP