简体   繁体   中英

How do you write an IF ELSE inside a SELECT statement in MSSQL 2008?

Here is what I am trying to do:

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

Unfortunately realized this is not compatible with MSSQL2008. So tried writing an IF ELSE but that also is not working.

SELECT  IF d.ItemType = 'INVOICE'
   0
ELSE 
   BEGIN
      d.ItemType = 'PACKING'
      0
   ELSE
      1
   END  AS MissingDocuments
FROM  dbo.DocumentDetails AS D 

can you please tell me what am I doing wrong here ?

Use CASE ... WHEN . The most concise logic seems to be:

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

ie the Document is missing if it isn't 'Invoice' or 'Packing'

I think You Looking For Case When Try This..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM