SQL Server INLINE IF ELSE
I understand that this question (which shows up at the top of google results for "sql server inline if") is 2 years old, but with SQL Server 2012, the answers are somewhat outdated. It also appears to be a duplicate of SQL inline if statement type question, but that question (being an even older one), doesn't have an up to date answer either.
In SQL Server 2012 you can use the IIF
function:
IIF ( boolean_expression, true_value, false_value )
Example:
SELECT IIF(someColumn = 1, 'yes', 'no')
SQL Server does not have an inline if
statement, but it does have an inline case
that can be use to accomplish the same.
Case has two forms, one is:
select
case MyFlag
when 1 then 'YES'
when 0 then 'NO'
else 'OOPS'
end
from MyTable
where it's used just like a switch in C-like languages and the other is:
select
case
when MyFlag = 1 then 'YES'
when MyFlag = 0 then 'NO'
-- when some unrelated condition...
else 'OOPS'
end
from MyTable
where it senquentially evaluates a list of conditions and returns the first that is fulfiled.
P.S. The end
part is mandatory, and I usually forget that.
It's also usual for a simple case
stament to be completely inlined, like
select (case MyFlag when 1 then 'Yes' else 'No' end) as MyFlagDesc
Two possibilities:
(CASE WHEN condition1 THEN Value1 ELSE Value2 END)
or, the most complete solution:
(CASE value_to_check WHEN Value1 THEN Result1 [WHEN ... THEN ...] ELSE OtherResult END)