如何在MSSQL 2008中的SELECT语句中编写IF ELSE?

时间:2015-05-19 05:37:54

标签: sql-server sql-server-2008

以下是我要做的事情:

SELECT iif(d.ItemType = 'INVOICE', 0, iif(d.ItemType = 'PACKING', 0, 1)) AS MissingDocuments FROM dbo.DocumentDetails AS D

不幸的是意识到这与MSSQL2008不兼容。所以尝试写一个IF ELSE,但也没有用。

SELECT  IF d.ItemType = 'INVOICE'
   0
ELSE 
   BEGIN
      d.ItemType = 'PACKING'
      0
   ELSE
      1
   END  AS MissingDocuments
FROM  dbo.DocumentDetails AS D 
你可以告诉我这里我做错了什么吗?

2 个答案:

答案 0 :(得分:6)

使用CASE ... WHEN。最简洁的逻辑似乎是:

SELECT 
  CASE WHEN d.ItemType IN ('INVOICE', 'PACKING') THEN 0 ELSE 1 END
     AS MissingDocuments 
FROM dbo.DocumentDetails AS d

即。如果文件不是“发票”或“包装”

,则该文件丢失

答案 1 :(得分:2)

我认为你在寻找Case When 试试这个..

SELECT 
 case when d.ItemType = 'INVOICE' or d.ItemType = 'PACKING'
 then  0
 ELSE
  1
 END  AS MissingDocuments
FROM  dbo.DocumentDetails AS D