Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am using MS Sql Server 2008. My query has the code

SQL
WHERE RepCode = @RepCode


When @RepCode is set to a non-null value, the query behaves as I would expect. When I set the parameter to DBNull.Value, the query returns nothing, even though there is data that should be returned. If I rewrite it

SQL
WHERE RepCode IS @RepCode


then the query works correctly for a null value but not for a non-null value.

I assume that there is some way to write a parameterized query where the parameter may or may not be null that will always return the correct value. How would I do this?
Posted

You have pretty much discovered the reason for the problem. NULL is never equal to anything, not even to another NULL.

One workaround for this is that you eliminate NULL's from the comparison by replacing it with another value. Perhaps the easiest way is to use COALESCE[^]. Using that, your example would be something like:
SQL
WHERE COALESCE(RepCode, -1) = COALESCE(@RepCode, -1)

So the idea is that you replace the NULL with some other value.

Important: Just make sure that the value does not exist in the data since that would bring false results.
 
Share this answer
 
Comments
Gregory Gadow 7-Sep-11 16:26pm    
D'oh! Yup, that works: COALESCE(RepCode, '') = COALESCE(@RepCode, ''). One of those solutions that is too obvious. Thanks.
Wendelius 7-Sep-11 16:40pm    
You're welcome :)
It doesn't help you specifically, but MySQL has the <=> operator, called the "Null-safe equal-to" operator, or the "spaceship" operator.

I don't think T-SQL has this :(
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900