2

I'm trying to write something like :

SELECT *
FROM MyTable m
WHERE m.Category = CASE WHEN @Category IS NULL THEN m.Category ELSE @Category END

Basically, I need lines where m.Category equals @Category if this one has a value ; else, I need all lines.

BUT if m.Category has NULL value, the line is NOT send back because SQL needs something lile WHERE m.Category IS NULL and not WHERE m.Category = NULL.

So, how could I modify my request to tell to SQL : "I need ALL lines if @Category is null (even lines where m.Category is null), but if @Category has a value, I just need lines where m.Category matches @Category ?

1 Answer 1

3

you can write it like this:

select *
from MyTable m
where @Category is null or m.Category = @Category
Sign up to request clarification or add additional context in comments.

3 Comments

Ok, it was so easy I didn't even think about it... Thanks a lot
@roman-pekar - what do you call this? I used it about 5 years ago and had the need for it today and I couldn't for the life of me remember what it is called.
@Steven well I don't know, not sure it has some specific name

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.