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()))



 

3 comments:

  1. Good articles, Have you heard of Mr Benjamin, Email: 247officedept@gmail.com --WhatsApp Contact:+1-9893943740-- who work with funding service they grant me loan of $95,000.00 to launch my business and I have been paying them annually for two years now and I still have 2 years left although I enjoy working with them because they are genuine Loan lender who can give you any kind of loan.

    ReplyDelete
  2. The article looks magnificent, but it would be beneficial if you can share more about the suchlike subjects in the future. Keep posting. china mosfet manufacturer

    ReplyDelete
  3. Good post, if anyone wants to read more on SQL case, check

    Understanding SQL Server Case With Example

    ReplyDelete

If you have any doubt, please let me know.

Popular Posts