How do I perform an IF…THEN in an SQL SELECT?

前端 未结 30 1796
梦如初夏
梦如初夏 2020-11-21 22:50

How do I perform an IF...THEN in an SQL SELECT statement?

For example:

SELECT IF(Obsolete = \'N\' OR InStock = \'Y\' ? 1 :          


        
相关标签:
30条回答
  • 2020-11-21 23:27
      SELECT IIF(Obsolete = 'N' OR InStock = 'Y',1,0) AS Saleable, * FROM Product
    
    0 讨论(0)
  • 2020-11-21 23:27

    You can have two choices for this to actually implement:

    1. Using IIF, which got introduced from SQL Server 2012:

      SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
      
    2. Using Select Case:

      SELECT CASE
          WHEN Obsolete = 'N' or InStock = 'Y'
              THEN 1
              ELSE 0
          END as Saleable, *
          FROM Product
      
    0 讨论(0)
  • 2020-11-21 23:27

    Question:

    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;
    

    Using aliases -- p in this case -- will help prevent issues.

    0 讨论(0)
  • 2020-11-21 23:29

    Use pure bit logic:

    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
    

    See working demo: if then without case in SQL Server.

    For start, you need to work out the value of true and false for selected conditions. Here comes two NULLIF:

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

    combined together gives 1 or 0. Next use bitwise operators.

    It's the most WYSIWYG method.

    0 讨论(0)
  • 2020-11-21 23:30

    It will be something like that:

    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;
    
    0 讨论(0)
  • 2020-11-21 23:32
    SELECT  
    (CASE 
         WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                                ELSE 'NO' 
     END) as Salable
    , * 
    FROM Product
    
    0 讨论(0)
提交回复
热议问题