Case Expression in SQL Server

Syntax of CASE Expression:

CASE Expression
WHEN CONDITION1 THEN RESULT1
WHEN CONDITION2 THEN RESULT2
WHEN CONDITION3 THEN RESULT3
ELSE
RESULT4
END


Let us now see a practical example for the same. Write the following script in the SQL Server,

  1. DECLARE @Student table  
  2. (  
  3.    ID int identity primary key,  
  4.    Name varchar(20),  
  5.    Gender Char(1),  
  6.    Marks int  
  7. )  
  8.   
  9. INSERT INTO @Student  
  10. SELECT 'Nitin Tyagi','M',40  
  11. UNION  
  12. Select 'Jay Malik','M',50  
  13. UNION  
  14. SELECT 'Swati Singh','F',30  
  15.   
  16. Select ID,Name,Marks,Gender=(CASE GENDER  
  17. WHEN 'M' THEN 'MALE'  
  18. WHEN 'F' THEN 'FEMALE'  
  19. END), Status=(CASE   
  20. WHEN MARKS>=40 THEN 'PASS'  
  21. WHEN MARKS<=40 THEN 'FAIL'  
  22. END)   
  23. from @Student  
Here we have a table variable, Student, that has the basic details of the student. We capture the Name, Gender and marks of the student in the table. Now using CASE expression we will modify a few details and display it in the result set. First we will check if the Gender has n ‘M’ letter then it should be displayed as ‘Male’ otherwise ‘Female’.

Similarly we check for the status of the students. If the marks of the student are greater than 40 then we will display the status as ‘PASS’ but if the marks are less then 40 then it would be displayed as ‘FAIL’.

Let us now execute the preceding script and check the output.



We can see now that Gender is displayed as per the case expression and so is the status. This is how we can use CASE Expression.

 

Ebook Download
View all
Learn
View all