4

I want to only use the where condition if Make is not equal to '0'. This is what I have tried. This is a snippet from the stored proc. Query works only when Make is not 0. When it is '0' it fails.

This is not a null check. @Make is a varchar. How it is implemented is either it will be '0' or it will be a string e.g 'mazda'.

select *
from In_Inventory
where
and Make = case 
when @Make != '0'
Then @Make
end
1
  • 1
    Just for your own understanding, the reason this fails is because your case only returns a value when make != 0. If Make would be 0 your query would just read "and Make =". Then again, there's no reason to use a case here. See below for better approaches (such as using an OR).
    – Jens
    Commented Jun 28, 2016 at 8:28

4 Answers 4

2

Try something like this

SELECT
*
FROM In_Inventory
WHERE @Make = 0
OR Make = @Make 
3
  • Thanks for the quick response but it isn't going to work in this scenario. What I need is if the value coming into the @Make variable in the stored proc is equal to '0' do not filter on make. If the variable is equal to anything else filter on make. "WHERE Make = 0" would be never be used because the Make column is a varchar with values like "mazda" etc
    – JKerny
    Commented Jun 28, 2016 at 7:59
  • @JeremyKern I've just updated my answer. If @ Make = 0 then don't do anything, otherwise do Make = @ Make. Is this what you're after? Commented Jun 28, 2016 at 8:04
  • This looks to be what I am after. I'll try it when I'm back at work tomorrow
    – JKerny
    Commented Jun 28, 2016 at 10:37
1

You can't use a case expression to return syntactic elements (such as a where clause), only values. However, you could get the same behavior with a simple in condition:

SELECT *
FROM   In_Inventory
WHERE  @Make IN ('0', Make)
1

Try this,

SELECT
*
FROM In_Inventory
WHERE @Make = 0
OR Make = @Make
1

Try like this,

SELECT *
FROM In_Inventory
WHERE (
        Make = 0
        OR Make = @Make
        )

Your Answer

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

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