如何在SQL SELECT语句中执行IF…THEN?

例如:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

当前回答

如果您是第一次将结果插入表中,而不是将结果从一个表传输到另一个表,这在Oracle 11.2g中适用:

INSERT INTO customers (last_name, first_name, city)
    SELECT 'Doe', 'John', 'Chicago' FROM dual
    WHERE NOT EXISTS
        (SELECT '1' from customers
            where last_name = 'Doe'
            and first_name = 'John'
            and city = 'Chicago');

其他回答

 SELECT
   CASE 
      WHEN OBSOLETE = 'N' or InStock = 'Y' THEN 'TRUE' 
      ELSE 'FALSE' 
   END AS Salable,
   * 
FROM PRODUCT

问题:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

答案:

Select 
  case when p.Obsolete = 'N' 
  or p.InStock = 'Y' then 1 else 0 end as Saleable, 
  p.* 
FROM 
  Product p;

使用别名(在本例中为p)将有助于防止出现问题。

SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 
             END AS Saleable, * 
FROM Product

为了完整起见,我想补充一点,SQL使用三值逻辑。表达式:

obsolete = 'N' OR instock = 'Y'

可能产生三种不同的结果:

| obsolete | instock | saleable |
|----------|---------|----------|
| Y        | Y       | true     |
| Y        | N       | false    |
| Y        | null    | null     |
| N        | Y       | true     |
| N        | N       | true     |
| N        | null    | true     |
| null     | Y       | true     |
| null     | N       | null     |
| null     | null    | null     |

例如,如果一个产品已经过时,但你不知道产品是否库存,那么你不知道该产品是否可销售。您可以按如下方式编写此三值逻辑:

SELECT CASE
           WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'
           WHEN NOT (obsolete = 'N' OR instock = 'Y') THEN 'false'
           ELSE NULL
       END AS saleable

一旦确定了它的工作原理,就可以通过决定null的行为将三个结果转换为两个结果。例如,这会将null视为不可销售:

SELECT CASE
           WHEN obsolete = 'N' OR instock = 'Y' THEN 'true'
           ELSE 'false' -- either false or null
       END AS saleable

对于使用SQL Server 2012的用户来说,IIF是一个已添加的功能,可以作为Case语句的替代。

SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *
FROM   Product