Advertisement

Latest Post

Saturday, 24 September 2016

How to use CASE in Sql server



The CASE keyword is used as a conditional operator that like the functionality of an IF-THEN-ELSE statement.
Syntax:

CASE

   WHEN condition_1 THEN result_1
   WHEN condition_2 THEN result_2
   ...
   WHEN condition_n THEN result_n

   ELSE result

END

Example: 

BEGIN
DECLARE @EnumId INT= 1
      -- Declare the return variable here
      DECLARE @result VARCHAR(100)
      SET @result = (SELECT
      CASE WHEN @EnumId = 1 THEN 'Active'
             WHEN @EnumId = 2 THEN 'Deceased'
             WHEN @EnumId = 3 THEN 'Inactive'
             WHEN @EnumId = 4 THEN 'Discharged'
             ELSE
             ''
      END)       
      select  @result
END



                

Government Jobs