Let’s imagine there is a table Product with columns ProductId (smallint), Title (nullable nvarchar(100)) and Price (money). A title can be null.
There is a query which must return the products matching a specific title and a specific price:
using (SqlCommand getProducts = new SqlCommand("select ProductId from Product where Title = @title and Price = @price", sqlConnection))
{
getProducts.Parameters.AddWithValue("@title", title);
getProducts.Parameters.AddWithValue("@price", price);
}
When executing the following code with title set to null (or probably also to an empty string), for SQL Server, the comparison will be:
[...] where Title = NULL and Price = 123
which will return an empty set, since the correct syntax is:
[...] where Title is NULL and Price = 123
I could change the query string according to the null check of the title, but it will be unmaintainable.
Is there a clean way to make the comparison work without making the query string different when Title is null?
1 Answer