1

I have SQL table that contains null values for ex:

ID NAME CODE
1 Joe 123
2 Doe 456
3 Soe NULL

I want to check if the where clause parameter is null then return all table, what I tried:

@devCode int = NULL

SELECT * FROM myTable WHERE CODE = ISNULL(@devCode, CODE)

But the last row (ID 3) gets excluded when @devCode = NULL. I want that to be included too in result when the parameter is null.

p.s. I also tried IIF and CASE but the result is the same.

2
  • 1
    This is how null works... Doesn't match anything including null. Commented Mar 16, 2022 at 16:08
  • @SalmanA yes I learned that facing this, and I also learned that SET ANSI_NULLS OFF fix the problem nut it's not recommended to do so. Commented Mar 16, 2022 at 16:18

1 Answer 1

3

I think it will work

SELECT * FROM myTable WHERE CODE = @devCode OR @devCode IS Null
Sign up to request clarification or add additional context in comments.

2 Comments

Worked like a charm! I didn't think about it this way, I tried something similar but didn't work as expected: WHERE CODE = @devCode OR CODE IS Null Thank you!
you are welcome happy coding

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.