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:
|
||||
|
The
You only need to do the
SQL Server Denali (SQL Server 2012) adds the IIF statement which is also available in access: (pointed out by Martin Smith)
|
|||||||||||||||||||||
|
|
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. |
|||||||||||||
|
|
From SQL Server 2012 you can use the
This is effectively just a shorthand (albeit not standard SQL) way of writing I prefer the conciseness when compared with the expanded Both
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
Care must sometimes be taken to avoid parameter sniffing issues with this approach however. |
||||
|
|
|
Use CASE. Something like this.
|
|||||
|
|
You can find some nice examples in The Power of SQL CASE Statements, and I think the statement that you can use will be something like this (from 4guysfromrolla):
|
|||||||||
|
|
|||||
|
|
Microsoft SQL Server (T-SQL) In a select use:
In a where clause, use:
|
|||||
|
|
|||||
|
|
From this link, we can uderstand
Isn't this good enough for T-SQL ? |
|||||||||
|
|
Simple If else statement in sql server -
Nested If...else statement in sql server -
|
||||
|
|
|
And why not use pure bit logic?
See working demo: IF THEN WITHOUT CASE IN MSSQL For start, you need to work out the value of
combined together gives 1 or 0. Next use bitwise operators. It's the most WYSIWYG method. |
|||||||||||||
|
|
Use a CASE statement:
|
||||
|
|
|
|||
|
|
|
|||
|
|
|
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:
|
|||||
|
|
|||||
|
|
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.
|
|||||
|
|
A new feature IFF (we can simply use) added in sqlserver 2012
|
||||
|
|
|
|||||||||||||||||
|
|
For those who uses SQL Server 2012, IIF is a feature that has been added and works as an alternative to Case statements.
|
||||
|
|
use this if you want to compare more than one date |
||||
|
|
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
WHEREandCHECKbut notSELECT. – onedaywhen May 11 '16 at 16:06