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
Question ... SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
ANSI: Select case when p.Obsolete = 'N' or p.InStock = 'Y' then 1 else 0 end as Saleable, p.* FROM Product p;
Using aliases -- p in this case -- will help prevent issues.
Microsoft SQL Server (T-SQL)
In a select use:
In a where clause, use:
The case statement is your friend in this situation, and takes one of two forms:
The simple case:
The extended case:
You can even put case statements in an order by clause for really fancy ordering.
This isn't an answer, just an example of a CASE statement in use where I work. It has a nested CASE statement. Now you know why my eyes are crossed.
Use pure bit logic:
See working demo: IF THEN WITHOUT CASE IN MSSQL
For start, you need to work out the value of
true
andfalse
for selected conditions. Here comes two NULLIF:combined together gives 1 or 0. Next use bitwise operators.
It's the most WYSIWYG method.