In my table I got a column whose value is whether 0 or 1. If that column is 0 I output the value as 'no'; if 1 I should output as 'yes' for all rows. How can I do this only using SQL statement. Thanks
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
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')
-
3Upvoted, I prefer IIF versus CASE for simple boolean conditions because it is more streamlined – Breakskater Jul 14 '16 at 14:59
-
The chosen answer works, but in case of using DISTINCT only your IIF will do the job. useful answer. – maytham-ɯɐɥʇʎɐɯ Aug 20 '18 at 12:19
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)
Something like this:
SELECT
CASE YourColumn
WHEN 0 THEN 'no'
WHEN 1 THEN 'yes'
ELSE 'nothing'
END
FROM dbo.YourTable
I mixed three IIF in one line, I have three variables and I want to know which one is greater than zero but I know the order of priority PersonHomePhoneID , PersonWorkPhoneID and PersonCellPhoneID
IIF(@PersonHomePhoneID > 0 , @PersonHomePhoneID, IIF(@PersonWorkPhoneID > 0 , @PersonWorkPhoneID, IIF(@PersonCellPhoneID > 0 , @PersonCellPhoneID, 0)))
The answer of question :
IIF(column = 1 , 'yes', IIF(column = 0, 'no', ''))