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

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

    You can find some nice examples in The Power of SQL CASE Statements, and I think the statement that you can use will be something like this (from 4guysfromrolla):

    SELECT
        FirstName, LastName,
        Salary, DOB,
        CASE Gender
            WHEN 'M' THEN 'Male'
            WHEN 'F' THEN 'Female'
        END
    FROM Employees
    
    0 讨论(0)
  • 2020-11-21 23:10

    From this link, we can understand IF THEN ELSE in 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' 
    

    Isn't this good enough for T-SQL?

    0 讨论(0)
  • 2020-11-21 23:10
    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
    
    0 讨论(0)
  • 2020-11-21 23:11

    Use a CASE statement:

    SELECT CASE
           WHEN (Obsolete = 'N' OR InStock = 'Y')
           THEN 'Y'
           ELSE 'N'
    END as Available
    
    etc...
    
    0 讨论(0)
  • 2020-11-21 23:11
    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' )
    
    0 讨论(0)
  • 2020-11-21 23:12

    For those who uses SQL Server 2012, IIF is a feature that has been added and works as an alternative to Case statements.

    SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *
    FROM   Product 
    
    0 讨论(0)
提交回复
热议问题