Tuesday 27 September 2016

Alternative of long CASE statement in Sql server

Switch CASE is the special scalar expression or conditional statement in the SQL language which returns a single value based on the evaluation of a statement.
Here I am taking an example to find the today date
select case DATEPART(dw,GETDATE())
       when 1 then 'Sunday'
                   when 2 then 'Monday'
                   when 3 then 'Tuesday'
                   when 4 then 'Wednesday'
                   when 5 then 'Thursday'
                   when 6 then 'Friday'
                   when 7 then 'Saturday'
                   else 'AN'
                   END
                   as Today


  
Suppose here we have seven cases. If it is long then it will be the tedious task. We have alternative for that to create the derive table.
select x.[Today] from
( values                (1,'Sunday'),
                                                (2,'Monday'),
                                                (3,'Tuesday'),
                                                (4,'Wednesday'),
                                                (5,'Thursday'),
                                                (6,'Friday'),
                                                (7,'Saturday')
)x(ID,Today)
where x.ID= (DATEPART(dw,GETDATE()))



 

Popular Posts