如何执行IF...THENinSQL SELECT语句?
IF...THEN
SQL SELECT
例如:
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
该CASE语句是 SQL 中最接近 IF 的语句,所有版本的 SQL Server 都支持该语句。
CASE
SELECT CAST( CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 END AS bit) as Saleable, * FROM Product
CAST如果您希望结果为布尔值,则只需要使用运算符。如果您对 a 感到满意int,则此方法有效:
CAST
int
SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 END as Saleable, * FROM Product
CASE语句可以嵌入到其他CASE语句中,甚至可以包含在聚合中。
SQL Server Denali (SQL Server 2012) 添加了IIF语句,该语句也可用于访问( Martin Smith):
SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product