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

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

    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.

提交回复
热议问题