0

I am trying to put an if condition within a where clause and I cannot figure out the correct syntax for what I want.

The logic should be if a certain period is equal to a specific number then check to make sure pdftype is not null else then don't check it all.

Here's what I have so far:

where  
    g.ReportInstanceID = blah
    and rcr.FormID = blah
    and rcr.FormSectionID = blah
    and rcr.SubSectionID = blah
    and CASE rcr.DataCollectionPeriodID 
           WHEN 163 THEN (PDFType IS NOT NULL)
        END
2
  • I would use multiple conditions with OR as shown in answer below, but you can use CASE in WHERE: AND CASE WHEN rcr.DataCollectionPeriodID = 163 THEN PDFType ELSE 'X' END IS NOT NULL Commented Jan 30, 2017 at 18:31
  • This answer shows how a CASE expression can be used in a ON clause. The same works for a WHERE clause. Commented Jan 30, 2017 at 19:35

2 Answers 2

6

That's not how the CASE statement works. I think this does what you want:

where  g.ReportInstanceID = blah
    and rcr.FormID = blah
    and rcr.FormSectionID = blah
    and rcr.SubSectionID = blah
    and (
          (rcr.DataCollectionPeriodID = 163 and PDFType IS NOT NULL)
          or rcr.DataCollectionPeriodID <> 163
        )
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

. . .
AND CASE when rcr.DataCollectionPeriodID = 163 THEN
     case when PDFType is not null then 1 else 0 end
    else 1 END = 1

1 Comment

hi the code works but can you help to explain how the else 1 and end = 1 works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.