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
also how to use IIF in sql query?please give an example
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
IIF(condition, <value if condition is true>,<value if condition is false>)
SELECT IIF(10 > 5, 1,0)
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
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,
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
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...
F1 ,f2 F3 are field names
Open in new window