Link to home
Start Free TrialLog in
Avatar of Umesh Modi
Umesh Modi

asked on

how to use SELECT CASE in sql query?please give an example

how to use SELECT CASE in sql query?please give an example
also how to use IIF in sql query?please give an example
ASKER CERTIFIED SOLUTION
Avatar of rgn2121
rgn2121
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Pratima
Try this

F1 ,f2 F3 are field names
select 
					 CASE  WHEN (F1 > 0)
			 THEN 
				F1
			 WHEN  (F2 > 0)
			 THEN 
				F2
			 ELSE
			    F3
			  END
			From  TABLENAME

Open in new window


IIF(condition, <value if condition is true>,<value if condition is false>)
 
SELECT IIF(10 > 5, 1,0)

Open in new window

Avatar of SwamyN
SwamyN

hi umesh, try this
select case Column_Name when '1' then 'Yes' when '0' then 'No' else 'NA' end from Table_Name
The above query returns Yes, No or NA if the actual values of 'COlumn_Name' are 1, 0 or anything else respectively
For the MSSQL Server equivalent of IIF, you have to use case as
select case when CONDITION then  value1 else value2 end  from TABLES USED IN CONDITION
eg:
select case when 1 + 1= 2 then 'True' else 'False' end
select case when Column_Name = 1 then 'True' else 'False' end  from Table_Name
a couple of ways to use a case statement (and you can imbed them as well)

case condition when result then value
                        when result then value
                         else othervalue
                         end

or

case when condition then do_this_if_true else do_that end

or

case when condition then value
        when condition then value
        else other value
        end


For example,


select case when datename(dw,getdate()) like 'S%' then 'Weekend' else 'Workday' end as type_of_day
 
select case left(datename(dw,getdate()),2) when 'SU' then 'Church'
                                           when 'SA' then 'Golf'
                                           else 'Work'
                                           end as main_activity
 
 
-- or from a table...
 
select table_name, column_name, data_type+case when data_type like '%char%' then '('+convert(varchar,character_maximum_length)+')'
                                               when data_type = 'decimal' then '('+convert(varchar,numeric_precision)+','+convert(varchar,isnull(numeric_scale,0))+')'
                                               else '' end as type_of_column
from information_schema.columns order by table_name, ordinal_position 

Open in new window

And we can all hold our collective breaths as we wait for feedback from the author.
Or publish another variant. There is no embedded ones yet...
Looks like I was wrong in the previous post, because the only one worthy of 50 points with all the great examples, is the embedded one...