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 ?

Upvotes: 3

Views: 39072

Answers (2)

Dhaval
Dhaval

Reputation: 2379

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 

Upvotes: 2

StuartLC
StuartLC

Reputation: 107277

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

i.e. the Document is missing if it isn't 'Invoice' or 'Packing'

Upvotes: 7

Related Questions