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

前端 未结 30 1838
梦如初夏
梦如初夏 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:18
    SELECT CASE WHEN profile.nrefillno = 0 THEN 'N' ELSE 'R'END as newref
    From profile
    
    0 讨论(0)
  • 2020-11-21 23:18

    If you're inserting results into a table for the first time, rather than transferring results from one table to another, this works in 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');
    
    0 讨论(0)
  • 2020-11-21 23:18

    Using SQL CASE is just like normal If / Else statements. In below query, If obsolete value = 'N' or If InStock value = 'Y' Then Output will be 1. Otherwise output will be 0. Then we put that 0 or 1 value under the Salable Column.

    SELECT
          CASE 
            WHEN obsolete = 'N' OR InStock = 'Y' 
            THEN 1 
            ELSE 0 
          END AS Salable
          , * 
    FROM PRODUCT
    
    0 讨论(0)
  • 2020-11-21 23:20

    Use CASE. Something like this.

    SELECT Salable =
            CASE Obsolete
            WHEN 'N' THEN 1
            ELSE 0
        END
    
    0 讨论(0)
  • 2020-11-21 23:21

    From SQL Server 2012 you can use the IIF function for this.

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

    This is effectively just a shorthand (albeit not standard SQL) way of writing CASE.

    I prefer the conciseness when compared with the expanded CASE version.

    Both IIF() and CASE resolve as expressions within a SQL statement and can only be used in well-defined places.

    The CASE expression cannot be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures.

    If your needs can not be satisfied by these limitations (for example, a need to return differently shaped result sets dependent on some condition) then SQL Server does also have a procedural IF keyword.

    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.

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

    Microsoft SQL Server (T-SQL)

    In a select, use:

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

    In a where clause, use:

    where 1 = case when Obsolete = 'N' or InStock = 'Y' then 1 else 0 end
    
    0 讨论(0)
提交回复
热议问题