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

前端 未结 30 1831
梦如初夏
梦如初夏 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:21

    As an alternative solution to the CASE statement, a table-driven approach can be used:

    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
    

    Result:

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

提交回复
热议问题