How do I perform an IF...THEN
in an SQL SELECT
statement?
For example:
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
How do I perform an IF...THEN
in an SQL SELECT
statement?
For example:
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
SELECT CAST(CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN ELSE 0 END AS bit) as Saleable, * FROM Product
The
CASE
statement is the closest to IF in SQL and is supported on all versions of SQL ServerYou only need to do the
CAST
if you want the result as a boolean value, if you are happy with anint
, this works:CASE
statements can be embedded in otherCASE
statements and even included in aggregates.SQL Server Denali (SQL Server 2012) adds the IIF statement which is also available in access: (pointed out by Martin Smith)
A new feature, IIF (that we can simply use), was added in SQL Server 2012:
As an alternative solution to the
CASE
statement table driven approach can be used.Result: