How can I perform if … then in the SQL SELECT statement?
For example:
select if (obsolete = 'n' or Instock = 'Y'? 1: 0) as saleable, * from Product
Question translation How to Perform An if … Then in An SQL SELECT? @eric labashosky
Answer 1, Authority 100%
The Case
statement is the nearest if
analogue in SQL and is supported in all versions of SQL Server.
Select Cast (
Case
WHEN OBSOLETE = 'N' OR Instock = 'Y'
THEN 1.
ELSE 0.
END AS BIT) as saleable, *
From Product.
The only case when you need to use Cast
– if you need a result in the form of a boolean value; If you are satisfied with the type int
, the solution is as follows:
select case
WHEN OBSOLETE = 'N' OR Instock = 'Y'
THEN 1.
ELSE 0.
END AS SALEABLE, *
From Product.
Operator Case
You can implement in another Operator Case
and even include in the aggregated object.
SQL Server Denali (SQL Server 2012) adds an operator iif also present in Access : (It is noted Martin Smith )
select iIF (obsolete = 'n' or instock = 'y', 1, 0) as selable, * from Product
Answer translation How to Perform An If … Then in An SQL SELECT? @Darrel Miller .