1

I'm attempting to create a parameterized where statement using COALESCE in SQL 2008, and I have the example of:

Select * 
From Receipts 
Where Receipts.FunctionCode = COALESCE(@FunCode, Receipts.FunctionCode)

in hope that if i pass in NULL in @FunCode, it will pull all 7050 records. However its only pulling back 236 records, and same as if the where was this: Where Receipts.FunctionCode = Receipts.FunctionCode

Can someone explain what logic is wrong for me? To me, this where statement should always pull 100% back the database

2
  • Well, are there values where Receipts.FunctionCode are NULL? Commented Mar 30, 2015 at 19:00
  • Null = Null isn't true in SQL. Commented Mar 30, 2015 at 19:01

1 Answer 1

3

That is due to the NULL values present in the FunctionCode column try this instead. This will use index created on FunctionCode if any

Select * 
From Receipts 
Where Receipts.FunctionCode = @FunCode or @FunCode IS NULL
Sign up to request clarification or add additional context in comments.

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.