如何在SQL SELECT语句中执行IF…THEN?

例如:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product

当前回答

您可以有两种选择来实现:

使用从SQL Server 2012引入的IIF:选择IIF((过时=“N”或InStock=“Y”),1,0)作为可销售产品,*来自产品使用Select Case:选择大小写当过时=“N”或InStock=“Y”时然后1其他0结束销售*FROM产品

其他回答

作为CASE语句的替代解决方案,可以使用表驱动方法:

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

结果:

ID          Obsolete   InStock    Saleable
----------- ---------- ---------- -----------
1           N          Y          1
2           A          B          0
3           N          B          1
4           A          Y          1
SELECT CASE WHEN profile.nrefillno = 0 THEN 'N' ELSE 'R'END as newref
From profile

使用SQL CASE与普通的If/Else语句一样。在下面的查询中,如果过时值=“N”或InStock值=“Y”,则输出将为1。否则,输出将为0。然后我们将0或1值放在Salable列下。

SELECT
      CASE
           WHEN obsolete = 'N' OR InStock = 'Y'
          THEN 1
        ELSE 0
      END AS Salable
      , *
FROM PRODUCT

通过此链接,我们可以了解T-SQL中的IF THEN ELSE:

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' 

这对t-SQL不够好吗?

你可以在SQL CASE语句的威力中找到一些很好的例子,我认为你可以使用的语句应该是这样的(来自4guysfromrolla):

SELECT
    FirstName, LastName,
    Salary, DOB,
    CASE Gender
        WHEN 'M' THEN 'Male'
        WHEN 'F' THEN 'Female'
    END
FROM Employees