4

I have 2 fields I want to send values to within a WHERE statement.

  • If a variable = 0 then set 2 field values to 100.
  • If the variable = 1 then set those same 2 field values to 101.

In my imaginary world, somehow this would work:

Where CASE WHEN @ReportType = 0 THEN 
    od.StatusCd = 100 AND odm.StatusCd = 100
WHEN @ReportType = 1 THEN 
    od.statusCd = 101 AND odm.StatusCd = 101
End
And od.CompletionDate between ....
And so on....

I know this is wrong. But this is where I am at right now.

2
  • 6
    You are close, you can use OR around the conditions with no CASE.
    – Taryn
    Oct 7, 2014 at 20:37
  • where/what comparisons you are doing after sending values ? if i understand it correct you are just assigning values and no proper usage of 'where'.correct me if i got it wrong
    – Recursive
    Oct 8, 2014 at 13:33

3 Answers 3

9

If I have understood what you are trying to do, this should work :

Where 
(
(@ReportType = 0 AND od.StatusCd = 100 AND odm.StatusCd = 100)
OR
(@ReportType = 1 AND od.statusCd = 101 AND odm.StatusCd = 101)
)
And od.CompletionDate between ....
And so on....
1

Alternatively you could rewrite your CASE conditions in the form of a join, like below:

...
INNER JOIN
  (
    VALUES (0, 100, 100), (1, 101, 101)
  ) AS v (ReportType, odStatusCd, odmStatusCd)
ON
  @ReportType = v.ReportType
  AND od.statusCd = v.odStatusCd
  AND odm.StatusCd = v.odmStatusCd
WHERE
  od.CompletionDate between ...
  AND ...

Although somewhat less readable, this would avoid using OR and thus might result in a better (more efficient) execution plan. (You would need to test that.)

0

You could also just do

WHERE od.StatusCd = 100 + @ReportType AND odm.StatusCd = 100 + @ReportType

Or you could declare a new variable with the value in:

DECLARE @StatusCd = 100 + @ReportType

Keep it simple.

1
  • Oops, this showed up as new activity, and I didn't notice it was such an old question. Nevertheless I think I'll leave this answer here, since I think it adds value!
    – cf_en
    Apr 19, 2016 at 8:07

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.