2010年9月3日 星期五

How do you perform an if then in a sql select statment

http://stackoverflow.com/questions/63447/how-do-you-perform-an-if-then-in-a-sql-select

SELECT CAST(CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1
ELSE 0 END AS bit) as Salable, *
FROM Product

===============================

The case statement is your friend in this situation, and takes one of two forms:

The simple case:

SELECT CASE WHEN THEN
WHEN THEN
ELSE
END
FROM

The extended case:

SELECT CASE WHEN THEN
WHEN THEN
ELSE
END
FROM


You can even put case statements in an order by clause for really fancy ordering.

===========================
SELECT *,
Salable =
CASE
WHEN (Obsolete = 'N' AND InStock = 'Y) THEN true
ELSE false
END
FROM Product

沒有留言:

張貼留言