Friday, January 30, 2015

A Simple Use of SQL CASE Expression

We normally use ‘SELECT’ query during database operations to fetch the data from database in SQL, like

select * from tbl_order_Master

Output



Let’s suppose we need to show Customer Name Virat to Virat Kohli during fetching the data via SELECT query in SQL SERVER.

In this circumastances we need to apply CASE in sql query like that

select (case when customerName='Virat' then 'Virat Kohli' else Customername end) as CustomerName ,Item ,Bill from tbl_order_Master

Output



How we can apply more than one cases in one SELECT Query –

Let’s suppose we need to show Customer Name Virat to Virat Kohli and Dhoni to MS Dhoni  during fetching the data via one SELECT query in SQL SERVER.

In this circumastances we need to apply Two CASES in sql query like that

select (case when customerName='Virat' then 'Virat Kohli' else case When customername='Dhoni' then 'MS Dhoni' else  Customername end end) as CustomerName ,Item ,Bill from tbl_order_Master

Output



USE- Now the question is when we use these cases or in Which circumastances we need to apply this.

Answer- Normally we use these cases when we don’t want to change the entry in database permanently and want to display different entry instead of actual entry for some places .

For Example- We want to create a report in which we need to show the Customers name who have placed the report, and there is a Customer Name Kohli  and we want to show that Virat Kohli without changing the name entry permanently then we use CASE in SELECT query

                                              Author- Er. Rahul Kr. Yadav

No comments:

Post a Comment