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
From this link, we can uderstand
IF THEN ELSE
inT-SQL
:Isn't this good enough for T-SQL ?
From SQL Server 2012 you can use the
IIF
function for this.This is effectively just a shorthand (albeit not standard SQL) way of writing
CASE
.I prefer the conciseness when compared with the expanded
CASE
version.Both
IIF()
andCASE
resolve as expressions within a SQL Statement and can only be used in well defined places.If your needs can not be satisfied by these limitations (for example a need to return differently shaped result sets dependant on some condition) then SQL Server does also have a procedural
IF
Keyword.Care must sometimes be taken to avoid parameter sniffing issues with this approach however.
Use CASE. Something like this.
If you're inserting results into a table for the first time, rather than transferring results from one table to another, this works in Oracle 11.2g:
Use a CASE statement: