如何在SQL SELECT中执行IF ... THEN?

时间:2008-09-15 14:34:09

标签: sql sql-server tsql if-statement case

如何在IF...THEN声明中执行SQL SELECT

例如:

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

30 个答案:

答案 0 :(得分:1608)

CASE语句最接近SQL中的IF,并且在所有版本的SQL Server上都受支持

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

如果您希望将结果作为布尔值,则只需执行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语句,该语句也可在access中找到:(由Martin Smith指出)

SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product

答案 1 :(得分:307)

在这种情况下,case语句是你的朋友,并采用以下两种形式之一:

简单的案例:

SELECT CASE <variable> WHEN <value>      THEN <returnvalue>
                       WHEN <othervalue> THEN <returnthis>
                                         ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

扩展案例:

SELECT CASE WHEN <test>      THEN <returnvalue>
            WHEN <othertest> THEN <returnthis>
                             ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

你甚至可以将case语句放在order by子句中,以便进行真正的花哨排序。

答案 2 :(得分:245)

从SQL Server 2012开始,您可以使用IIF function

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

这实际上只是写CASE的简写(尽管不是标准的SQL)方式。

与扩展的CASE版本相比,我更喜欢简洁。

IIF()CASE都解析为SQL语句中的表达式,并且只能在定义良好的位置使用。

  

CASE表达式不能用于控制执行流程   Transact-SQL语句,语句块,用户定义的函数和   存储过程。

如果这些限制无法满足您的需求(例如需要根据某些条件返回不同形状的结果集),那么SQL Server也会有一个程序IF关键字。

IF @IncludeExtendedInformation = 1 
  BEGIN 
      SELECT A,B,C,X,Y,Z 
      FROM   T 
  END 
ELSE 
  BEGIN 
      SELECT A,B,C 
      FROM   T 
  END 

Care must sometimes be taken to avoid parameter sniffing issues with this approach however.

答案 3 :(得分:83)

你可以在 The Power of SQL CASE Statements 中找到一些不错的例子,我认为你可以使用的语句是这样的(来自4guysfromrolla):

SELECT
    FirstName, LastName,
    Salary, DOB,
    CASE Gender
        WHEN 'M' THEN 'Male'
        WHEN 'F' THEN 'Female'
    END
FROM Employees

答案 4 :(得分:74)

使用CASE。这样的事情。

SELECT Salable =
        CASE Obsolete
        WHEN 'N' THEN 1
        ELSE 0
    END

答案 5 :(得分:47)

SELECT  
(CASE 
     WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                            ELSE 'NO' 
 END) as Salable
, * 
FROM Product

答案 6 :(得分:44)

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

答案 7 :(得分:43)

通过此link,我们可以了解IF THEN ELSE中的T-SQL

IF EXISTS(SELECT *
          FROM   Northwind.dbo.Customers
          WHERE  CustomerId = 'ALFKI')
  PRINT 'Need to update Customer Record ALFKI'
ELSE
  PRINT 'Need to add Customer Record ALFKI'

IF EXISTS(SELECT *
          FROM   Northwind.dbo.Customers
          WHERE  CustomerId = 'LARSE')
  PRINT 'Need to update Customer Record LARSE'
ELSE
  PRINT 'Need to add Customer Record LARSE' 

这对T-SQL来说不够好吗?

答案 8 :(得分:42)

Microsoft SQL Server(T-SQL)

在选择使用中:

select case when Obsolete = 'N' or InStock = 'Y' then 'YES' else 'NO' end

在where子句中,使用:

where 1 = case when Obsolete = 'N' or InStock = 'Y' then 1 else 0 end

答案 9 :(得分:30)

SQL Server中的简单if-else语句:

DECLARE @val INT;
SET @val = 15;

IF @val < 25
PRINT 'Hi Ravi Anand';
ELSE
PRINT 'By Ravi Anand.';

GO

sql server中的嵌套If ... else语句 -

DECLARE @val INT;
SET @val = 15;

IF @val < 25
PRINT 'Hi Ravi Anand.';
ELSE
BEGIN
IF @val < 50
  PRINT 'what''s up?';
ELSE
  PRINT 'Bye Ravi Anand.';
END;

GO

答案 10 :(得分:24)

使用CASE声明:

SELECT CASE
       WHEN (Obsolete = 'N' OR InStock = 'Y')
       THEN 'Y'
       ELSE 'N'
END as Available

etc...

答案 11 :(得分:24)

使用纯位逻辑:

DECLARE @Product TABLE (
    id INT PRIMARY KEY IDENTITY NOT NULL
   ,Obsolote CHAR(1)
   ,Instock CHAR(1)
)

INSERT INTO @Product ([Obsolote], [Instock])
    VALUES ('N', 'N'), ('N', 'Y'), ('Y', 'Y'), ('Y', 'N')

;
WITH cte
AS
(
    SELECT
        'CheckIfInstock' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Instock], 'Y'), 1), 'N'), 0) AS BIT)
       ,'CheckIfObsolote' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Obsolote], 'N'), 0), 'Y'), 1) AS BIT)
       ,*
    FROM
        @Product AS p
)
SELECT
    'Salable' = c.[CheckIfInstock] & ~c.[CheckIfObsolote]
   ,*
FROM
    [cte] c

请参阅working demo: IF THEN WITHOUT CASE IN MSSQL

首先,您需要为所选条件计算truefalse的值。这里有两个NULLIF

for true: ISNULL(NULLIF(p.[Instock], 'Y'), 1)
for false: ISNULL(NULLIF(p.[Instock], 'N'), 0)

组合在一起得1或0.接下来使用bitwise operators

这是WYSIWYG方法最多的。

答案 12 :(得分:24)

SQL Server 2012中添加了一项新功能IIF(我们可以简单地使用):

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

答案 13 :(得分:19)

SELECT 1 AS Saleable, *
  FROM @Product
 WHERE ( Obsolete = 'N' OR InStock = 'Y' )
UNION
SELECT 0 AS Saleable, *
  FROM @Product
 WHERE NOT ( Obsolete = 'N' OR InStock = 'Y' )

答案 14 :(得分:14)

case statement some what similar to if in SQL server

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

答案 15 :(得分:13)

这不是一个答案,只是我工作中使用的CASE语句的一个例子。它有一个嵌套的CASE语句。现在你知道为什么我的眼睛交叉了。

 CASE orweb2.dbo.Inventory.RegulatingAgencyName
    WHEN 'Region 1'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
    WHEN 'Region 2'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
    WHEN 'Region 3'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
    WHEN 'DEPT OF AGRICULTURE'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactAg
    ELSE (
            CASE orweb2.dbo.CountyStateAgContactInfo.IsContract
                WHEN 1
                    THEN orweb2.dbo.CountyStateAgContactInfo.ContactCounty
                ELSE orweb2.dbo.CountyStateAgContactInfo.ContactState
                END
            )
    END AS [County Contact Name]

答案 16 :(得分:12)

如果您是第一次将结果插入表中,而不是将结果从一个表传输到另一个表,则可以在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');

答案 17 :(得分:10)

作为CASE语句的替代解决方案,可以使用表驱动方法。

DECLARE @Product TABLE (ID INT, Obsolete VARCHAR(10), InStock VARCHAR(10)) 
INSERT INTO @Product VALUES
(1,'N','Y'),
(2,'A','B'),
(3,'N','B'),
(4,'A','Y')

SELECT P.* , ISNULL(Stmt.Saleable,0) Saleable
FROM 
    @Product P
    LEFT JOIN 
        ( VALUES
            ( 'N', 'Y', 1 )
        ) Stmt (Obsolete, InStock, Saleable)
        ON  P.InStock = Stmt.InStock OR P.Obsolete = Stmt.Obsolete 

结果:

ID          Obsolete   InStock    Saleable
----------- ---------- ---------- -----------
1           N          Y          1
2           A          B          0
3           N          B          1
4           A          Y          1

答案 18 :(得分:9)

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

答案 19 :(得分:7)

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

答案 20 :(得分:6)

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

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

答案 21 :(得分:4)

使用SQL CASE就像普通的If / Else语句一样。 在下面的查询中,如果过时的值='N'或如果InStock的值='Y',则输出将为1。否则,输出将为0。 然后,将该0或1值放入“可销售列”下。

SELECT
      CASE 
        WHEN obsolete = 'N' OR InStock = 'Y' 
        THEN 1 
        ELSE 0 
      END AS Salable
      , * 
FROM PRODUCT

答案 22 :(得分:3)

要实现此目标,您有两种选择:

1)使用从SQL 2012引入的IIF:

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

2)使用Select Case:

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

答案 23 :(得分:2)

问题:

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;

使用别名-在这种情况下使用p-将有助于防止出现问题。

答案 24 :(得分:2)

会是这样的:

SELECT OrderID, Quantity,
CASE
    WHEN Quantity > 30 THEN "The quantity is greater than 30"
    WHEN Quantity = 30 THEN "The quantity is 30"
    ELSE "The quantity is under 30"
END AS QuantityText
FROM OrderDetails;

答案 25 :(得分:2)

我喜欢使用CASE语句,但是这个问题要求在SQL Select中输入IF语句。我过去使用过的是:

SELECT

   if(GENDER = "M","Male","Female") as Gender

FROM ...

就像excel或工作表IF语句一样,先有条件,然后是真条件,然后是假条件:

if(condition, true, false)

此外,您可以嵌套if语句(但随后应使用CASE:-)

(注意:这在MySQLWorkbench中有效,但在其他平台上可能无效)

答案 26 :(得分:1)

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

答案 27 :(得分:1)

出于完整性考虑,我要补充一点,SQL使用三值逻辑。表达式:

Error response from daemon: unauthorized: You don't have the needed permissions to perform this operation, and you may have invalid credentials. To authenticate your request, follow the steps in: https://cloud.google.com/container-registry/docs/advanced-authentication

可能会产生三个不同的结果:

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     |

弄清楚它是如何工作的,可以通过确定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

答案 28 :(得分:1)

您可以使用案例声明:

Select 
Case WHEN (Obsolete = 'N' or InStock = 'Y') THEN 1 ELSE 0 END Saleable,
Product.*
from Product

答案 29 :(得分:1)

refreshAccessToken()