Search This Blog

Thursday 1 September 2016

Sql Query Using Case (Decisions)

Like in programming we use if else check and switch cases to take decisions on run time based on the data

Same thing we can do during in Sql Query as well.

In most of the cases when we select the data from Sql Server by using Sql query we got the values 1,2,3 and so on for the columns containing data type bit.

To make this enum values usefull we have to convert enum values in to meaning full label.

Below is the example through which we can achieve this.

Select top 10
SMMBUSRELTABLE.CUSTACCOUNTNUM,
SMMBUSRELTABLE.BRMPriceLevel,
SMMBUSRELTABLE.CustGroup,
CASE SMMBUSRELTABLE.BRMAccountType
        WHEN '0' THEN 'Bushetts'
        WHEN '1' THEN 'Amnesty'
WHEN '2' THEN 'Business'
WHEN '3' THEN 'Family'
WHEN '4' THEN 'Internal'
WHEN '5' THEN 'Shareholder'
WHEN '6' THEN 'Staff'
WHEN '7' THEN 'Trade'
WHEN '8' THEN 'Standard(Corporate)'
WHEN '9' THEN 'Partnership'
WHEN '10' THEN 'Gulf'
WHEN '11' THEN 'Inter Island Card'
    END as BRMAccountType
from SMMBUSRELTABLE


Some time we have to check that for each specific row that we have fetch the column value is null or not and based on that we customize the value's in that column and show.

Below is the example to achieve this.

Select
CodePrimary,
CodeSecondary,
CASE 
        WHEN ADDRESStable.STREET IS NULL THEN 'NULL'
        ELSE 'Value Found'
    END as CustomerAddress 
from  ADDRESS as ADDRESStable


This was all related to the using of cases in Sql Query let me know if you have any issues on this.

Thanks
Muhammad Zahid.



No comments:

Post a Comment