如何在SQLSELECT中执行IF… THEN?

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

例如:

SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
4309540 次浏览
SELECT(CASEWHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'ELSE 'NO'END) as Salable, *FROM Product

用例。像这样的东西。

SELECT Salable =CASE ObsoleteWHEN 'N' THEN 1ELSE 0END
 SELECTCASEWHEN OBSOLETE = 'N' or InStock = 'Y' THEN 'TRUE'ELSE 'FALSE'END AS Salable,*FROM PRODUCT

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

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

如果您希望结果为布尔值,您只需要使用CAST运算符。如果您对int感到满意,这可以工作:

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

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

SQLServer Denali(SQLServer 2012)添加了IIF语句,该语句在访问中也可用(由martinsmith指出):

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

你可以在SQLCASE语句的力量中找到一些很好的例子,我认为你可以使用的语句是这样的(来自4guysfrom罗拉):

SELECTFirstName, LastName,Salary, DOB,CASE GenderWHEN 'M' THEN 'Male'WHEN 'F' THEN 'Female'ENDFROM Employees

微软SQL服务器(SQL)

select中,使用:

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

使用CASE语句:

SELECT CASEWHEN (Obsolete = 'N' OR InStock = 'Y')THEN 'Y'ELSE 'N'END as Available
etc...

在这种情况下,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子句中,以实现真正花哨的排序。

此链接,我们可以理解T-SQL中的IF THEN ELSE

IF EXISTS(SELECT *FROM   Northwind.dbo.CustomersWHERE  CustomerId = 'ALFKI')PRINT 'Need to update Customer Record ALFKI'ELSEPRINT 'Need to add Customer Record ALFKI'
IF EXISTS(SELECT *FROM   Northwind.dbo.CustomersWHERE  CustomerId = 'LARSE')PRINT 'Need to update Customer Record LARSE'ELSEPRINT 'Need to add Customer Record LARSE'

这对SQL来说还不够好吗?

从SQLServer 2012中,您可以使用#0函数

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

这实际上只是CASE的一种速记(尽管不是标准SQL)方式。

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

IIF()CASE都解析为SQL语句中的表达式,只能在定义明确的地方使用。

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

如果这些限制不能满足您的需求(例如,需要根据某些条件返回不同形状的结果集),那么SQLServer也有一个过程#0关键字。

IF @IncludeExtendedInformation = 1BEGINSELECT A,B,C,X,Y,ZFROM   TENDELSEBEGINSELECT A,B,CFROM   TEND

但是,有时必须注意避免使用这种方法的参数嗅探问题

如果您第一次将结果插入表中,而不是将结果从一个表传输到另一个表,这在oracle11.2g中有效:

INSERT INTO customers (last_name, first_name, city)SELECT 'Doe', 'John', 'Chicago' FROM dualWHERE NOT EXISTS(SELECT '1' from customerswhere last_name = 'Doe'and first_name = 'John'and city = 'Chicago');

使用纯位逻辑:

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 cteAS(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

工作演示:如果然后没有#0在SQL服务器

对于开始,您需要计算选定条件的truefalse的值。这里有两个NULLIF

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

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

这是最所见即所得的方法。

对于那些使用SQLServer 2012的人来说,IIF是一个已经添加的功能,可以替代Case语句。

SELECT IIF(Obsolete = 'N' OR InStock = 'Y', 1, 0) AS Salable, *FROM   Product
SELECT CASE WHEN profile.nrefillno = 0 THEN 'N' ELSE 'R'END as newrefFrom profile
case statement some what similar to if in SQL server
SELECT CASEWHEN Obsolete = 'N' or InStock = 'Y'THEN 1ELSE 0END as Saleable, *FROM Product

SQLServer中的简单if-else语句:

DECLARE @val INT;SET @val = 15;
IF @val < 25PRINT 'Hi Ravi Anand';ELSEPRINT 'By Ravi Anand.';
GO

SQLServer中嵌套的if… else语句-

DECLARE @val INT;SET @val = 15;
IF @val < 25PRINT 'Hi Ravi Anand.';ELSEBEGINIF @val < 50PRINT 'what''s up?';ELSEPRINT 'Bye Ravi Anand.';END;
GO

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

 CASE orweb2.dbo.Inventory.RegulatingAgencyNameWHEN 'Region 1'THEN orweb2.dbo.CountyStateAgContactInfo.ContactStateWHEN 'Region 2'THEN orweb2.dbo.CountyStateAgContactInfo.ContactStateWHEN 'Region 3'THEN orweb2.dbo.CountyStateAgContactInfo.ContactStateWHEN 'DEPT OF AGRICULTURE'THEN orweb2.dbo.CountyStateAgContactInfo.ContactAgELSE (CASE orweb2.dbo.CountyStateAgContactInfo.IsContractWHEN 1THEN orweb2.dbo.CountyStateAgContactInfo.ContactCountyELSE orweb2.dbo.CountyStateAgContactInfo.ContactStateEND)END AS [County Contact Name]

SQLServer 2012中添加了一个新功能IIF(我们可以简单使用):

SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
SELECT 1 AS Saleable, *FROM @ProductWHERE ( Obsolete = 'N' OR InStock = 'Y' )UNIONSELECT 0 AS Saleable, *FROM @ProductWHERE NOT ( Obsolete = 'N' OR InStock = 'Y' )
  SELECT IIF(Obsolete = 'N' OR InStock = 'Y',1,0) AS Saleable, * FROM Product
SELECT CASE WHEN Obsolete = 'N' or InStock = 'Y' THEN 1 ELSE 0END AS Saleable, *FROM Product

作为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) SaleableFROM@Product PLEFT 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          12           A          B          03           N          B          14           A          Y          1
SELECTCAST(CASE WHEN Obsolete = 'N'or InStock = 'Y' THEN ELSE 0 END AS bit) as Saleable, *FROMProduct

提问:

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

ANSI:

Selectcase when p.Obsolete = 'N'or p.InStock = 'Y' then 1 else 0 end as Saleable,p.*FROMProduct p;

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

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

  1. 使用从SQLServer 2012引入的IIF:

    SELECT IIF ( (Obsolete = 'N' OR InStock = 'Y'), 1, 0) AS Saleable, * FROM Product
  2. Using Select Case:

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

它将是这样的:

SELECT OrderID, Quantity,CASEWHEN Quantity > 30 THEN "The quantity is greater than 30"WHEN Quantity = 30 THEN "The quantity is 30"ELSE "The quantity is under 30"END AS QuantityTextFROM OrderDetails;

为了完整起见,我想补充SQL使用三值逻辑。表达式:

obsolete = 'N' OR instock = 'Y'

可以产生三种不同的结果:

| obsolete | instock | saleable ||----------|---------|----------|| Y        | Y       | true     || Y        | N       | false    || Y        | null    | null     || N        | Y       | true     || N        | N       | true     || N        | null    | true     || null     | Y       | true     || null     | N       | null     || null     | null    | null     |

例如,如果一个产品已经过时,但你不知道产品是否缺货,那么你就不知道产品是否可以销售。你可以写这个三值逻辑如下:

SELECT CASEWHEN obsolete = 'N' OR instock = 'Y' THEN 'true'WHEN NOT (obsolete = 'N' OR instock = 'Y') THEN 'false'ELSE NULLEND AS saleable

一旦你弄清楚它是如何工作的,你可以通过决定null的行为将三个结果转换为两个结果。例如。这会将null视为不可销售:

SELECT CASEWHEN obsolete = 'N' OR instock = 'Y' THEN 'true'ELSE 'false' -- either false or nullEND AS saleable

使用SQLCASE就像普通的if/Else语句一样。在下面的查询中,如果obsolete value='N'或Instock value='Y',则输出将为1。否则输出将为0。然后我们将0或1值放在可销售列下。

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

我喜欢使用CASE语句,但问题要求在SQL选择中使用IF语句。我过去使用的是:

SELECT
if(GENDER = "M","Male","Female") as Gender
FROM ...

这就像Excel或工作表IF语句,其中有一个条件,然后是true条件,然后是false条件:

if(condition, true, false)

此外,您可以嵌套如果语句(但随后使用应该使用CASE:-)

(注意:这适用于mysql工作台,但可能不适用于其他平台)

您可以使用案件语句:

SelectCase WHEN (Obsolete = 'N' or InStock = 'Y') THEN 1 ELSE 0 END Saleable,Product.*from Product
SELECTif((obsolete = 'N' OR instock = 'Y'), 1, 0) AS saleable, *FROMproduct;

有多个条件。

SELECT
(CASEWHEN RIGHT((LEFT(POSID,5)),4) LIKE '1001' THEN 'DM'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1002' THEN 'GS'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1003' THEN 'MB'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1004' THEN 'MP'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1005' THEN 'PL'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1008' THEN 'DM-27'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1011' THEN 'PB'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1012' THEN 'UT-2'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1013' THEN 'JGC'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1014' THEN 'SB'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1015' THEN 'IR'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1016' THEN 'UT-3'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1017' THEN 'UT-4'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1019' THEN 'KR'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1020' THEN 'SYB-SB'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1021' THEN 'GR'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1022' THEN 'SYB-KP'WHEN RIGHT((LEFT(POSID,5)),4) LIKE '1026' THEN 'BNS'
ELSE ''END) AS OUTLET
FROM matrixcrm.Transact