0

I have to select rows following some variables which will switch on or off some conditions, like:

SELECT *
FROM table
WHERE field =
   CASE @param
       WHEN NULL THEN field
       ELSE @param
   END

In another words.. I want to compare only if @param is not null, but my select doesn't work. How can I do it?

Thanks!

1
  • Your code should work except when field has a NULL value. Commented Nov 19, 2015 at 14:32

3 Answers 3

2

When @param is null it will use field, when @param is not null it will use @param:

SELECT *
FROM table
WHERE field = ISNULL(@param,field)

But field = field will always be true. So what you might want is:

SELECT *
FROM table
WHERE field = @param
    and @param is not null
Sign up to request clarification or add additional context in comments.

Comments

2

Why use a Case for a single switch? an OR statement should do the trick.

SELECT *
FROM table
WHERE @param IS NULL OR Field = @Param

Comments

0

Should be like this:

SELECT *
FROM table
WHERE field =
   CASE 
   WHEN @param IS NULL THEN field
   ELSE @param
END

Comments

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.