Wednesday 25 September 2013

Using case statement in sql query on SQLServer database.

Say there is a table employee_master and we are going to use 5 fields

emp_code, emp_name, emp_sex, emp_grade and emp_category

last three fields
i.   emp_sex have value 'M' and 'F' (need to output 'Male' for 'M' and 'Female' for 'F')
ii.  emp_grade have value 'S' and 'W' (need to output 'Staff' for 'S' and 'Worker' for 'W')
iii. emp_category have value 'P' and 'T' (need to output 'Permanent' for 'P' and 'Temporary' for 'T')

Now this is the select statement using case statement

select emp_code,
          emp_name,
          (case when emp_sex='M' then 'Male' else case when emp_sex='F' then 'Female' else '' end end)
          as emp_sex,
          (case when emp_grade='S' then 'Staff' else case when emp_grade='W' then 'Worker' else '' end
          end)    as emp_grade,
          (case when emp_category='P' then 'Permanent' else case when emp_category='T' then
          'Temporary' else '' end) as emp_category
          from employee_master
          order by emp_code

       Now look into the case statement. For every case statement there is another nested case
       statement. "case when condition then value else (another nested case statement on the else part)
       end"

       I this way we can write multiple case statement just like next if else statement.
      
        end)    as emp_grade,
       



No comments: