it-swarm.cn

如何在SQL SELECT中执行IF ... THEN?

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

例如:

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

CASE语句最接近SQL中的IF,并且在所有版本的SQL Server上都受支持

SELECT CAST(
             CASE 
                  WHEN Obsolete = 'N' or InStock = 'Y' 
                     THEN 1 
                  ELSE 0 
             END AS bit) as Saleable, * 
FROM Product

如果你想把结果作为一个布尔值,你只需要做CAST,如果你对int感到满意,这可行: 

SELECT CASE 
            WHEN Obsolete = 'N' or InStock = 'Y' 
               THEN 1 
               ELSE 0 
       END as Saleable, * 
FROM Product

CASE语句可以嵌入到其他CASE语句中,甚至可以包含在聚合中。 

SQL Server Denali(SQL Server 2012)添加了 _ iif _ 语句,该语句也可用于 access :(由 Martin Smith指出

SELECT IIF(Obsolete = 'N' or InStock = 'Y', 1, 0) as Saleable, * FROM Product
1570
Darrel Miller

在这种情况下,case语句是你的朋友,并采用以下两种形式之一:

简单的案例:

SELECT CASE <variable> WHEN <value>      THEN <returnvalue>
                       WHEN <othervalue> THEN <returnthis>
                                         ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

扩展案例:

SELECT CASE WHEN <test>      THEN <returnvalue>
            WHEN <othertest> THEN <returnthis>
                             ELSE <returndefaultcase>
       END AS <newcolumnname>
FROM <table>

您甚至可以将case语句放在order by子句中,以实现真正的花哨排序。

301
Jonathan

从SQL Server 2012开始,您可以使用 IIFfunction 来实现此目的。

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

这实际上只是写CASE的简写(尽管不是标准的SQL)方式。 

与扩展的CASE版本相比,我更喜欢简洁。

IIF()CASE都作为SQL语句中的表达式解析,并且只能在定义良好的位置使用。 

CASE表达式不能用于控制 Transact-SQL语句,语句块,用户定义函数和存储过程的执行流程。

如果这些限制无法满足您的需求(例如需要根据某些条件返回不同形状的结果集),那么SQL Server也会有一个程序 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 

有时必须注意避免这种方法的参数嗅探问题。

236
Martin Smith

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

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

使用CASE。像这样的东西。

SELECT Salable =
        CASE Obsolete
        WHEN 'N' THEN 1
        ELSE 0
    END
73
palehorse
SELECT  
(CASE 
     WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                            ELSE 'NO' 
 END) as Salable
, * 
FROM Product
46
John Sheehan
 SELECT
   CASE 
      WHEN OBSOLETE = 'N' or InStock = 'Y' THEN 'TRUE' 
      ELSE 'FALSE' 
   END AS Salable,
   * 
FROM PRODUCT
43
Santiago Cepas

从这个 link ,我们可以理解IF THEN ELSE中的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' 

这对T-SQL来说不够好吗?

41
Ken

Microsoft SQL Server(T-SQL)

在选择使用中:

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

在where子句中,使用:

where 1 = case when Obsolete = 'N' or InStock = 'Y' then 1 else 0 end
40
user7658

SQL Server中简单的if-else语句:

DECLARE @val INT;
SET @val = 15;

IF @val < 25
PRINT 'Hi Ravi Anand';
ELSE
PRINT 'By Ravi Anand.';

GO

在SQL Server中嵌套If ... else语句 -

DECLARE @val INT;
SET @val = 15;

IF @val < 25
PRINT 'Hi Ravi Anand.';
ELSE
BEGIN
IF @val < 50
  PRINT 'what''s up?';
ELSE
  PRINT 'Bye Ravi Anand.';
END;

GO
29
Ravi Anand

在SQL Server 2012中添加了一个新功能 IIF (我们可以简单地使用它):

SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
23
sandeep rawat

使用纯位逻辑:

DECLARE @Product TABLE (
    id INT PRIMARY KEY IDENTITY NOT NULL
   ,Obsolote CHAR(1)
   ,Instock CHAR(1)
)

INSERT INTO @Product ([Obsolote], [Instock])
    VALUES ('N', 'N'), ('N', 'Y'), ('Y', 'Y'), ('Y', 'N')

;
WITH cte
AS
(
    SELECT
        'CheckIfInstock' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Instock], 'Y'), 1), 'N'), 0) AS BIT)
       ,'CheckIfObsolote' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Obsolote], 'N'), 0), 'Y'), 1) AS BIT)
       ,*
    FROM
        @Product AS p
)
SELECT
    'Salable' = c.[CheckIfInstock] & ~c.[CheckIfObsolote]
   ,*
FROM
    [cte] c

请参阅 工作演示:如果没有MSSQL中的情况

首先,您需要为所选条件计算truefalse的值。这里有两个 NULLIF

for true: ISNULL(NULLIF(p.[Instock], 'Y'), 1)
for false: ISNULL(NULLIF(p.[Instock], 'N'), 0)

组合在一起得到1或0.接下来使用 按位运算符

它是最 WYSIWYG 方法。

23
Tomasito

使用CASE声明:

SELECT CASE
       WHEN (Obsolete = 'N' OR InStock = 'Y')
       THEN 'Y'
       ELSE 'N'
END as Available

etc...
22
Christopher
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' )
18
onedaywhen
SELECT CASE WHEN profile.nrefillno = 0 THEN 'N' ELSE 'R'END as newref
From profile
15
atik sarker
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
13
Chanukya

这不是一个答案,只是我工作中使用的CASE语句的一个例子。它有一个嵌套的CASE语句。现在你知道为什么我的眼睛交叉了。 

 CASE orweb2.dbo.Inventory.RegulatingAgencyName
    WHEN 'Region 1'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
    WHEN 'Region 2'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
    WHEN 'Region 3'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactState
    WHEN 'DEPT OF AGRICULTURE'
        THEN orweb2.dbo.CountyStateAgContactInfo.ContactAg
    ELSE (
            CASE orweb2.dbo.CountyStateAgContactInfo.IsContract
                WHEN 1
                    THEN orweb2.dbo.CountyStateAgContactInfo.ContactCounty
                ELSE orweb2.dbo.CountyStateAgContactInfo.ContactState
                END
            )
    END AS [County Contact Name]
12
JustJohn

如果您是第一次将结果插入表中,而不是将结果从一个表传输到另一个表,则可以在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');
11
Robert B. Grossman

作为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
9
Serkan Arslan
SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0 
             END AS Saleable, * 
FROM Product
8
user8422856
  SELECT IIF(Obsolete = 'N' OR InStock = 'Y',1,0) AS Saleable, * FROM Product
6
SURJEET SINGH Bisht

对于那些使用SQL Server 2012的用户,IIF是一个已添加的功能,可作为Case语句的替代方案。

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

SELECT CAST(过时='N'或InStock ='Y',然后按0结束)作为可销售的情况,*来自产品

0
gii96

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

1)使用从SQL 2012引入的IIF:

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

2)使用Select Case:

SELECT CASE 
    WHEN Obsolete = 'N' or InStock = 'Y' 
        THEN 1 
        ELSE 0 
    END as Saleable, * 
    FROM Product
0
Shivi

问题... SELECT IF(已过时='N'OR InStock ='Y'?1:0)AS Salable,* FROM Product

ANSI:当p.Obsolete ='N'或p.InStock ='Y'时选择情况,然后1,否则0结束为Salable,p。* FROM Product p;

在这种情况下使用别名 - p将有助于防止出现问题。

0
David Cohn