As long as no other joins have to be made dynamically to check the value of a parameter that might matter, and the only dynamic part is the WHERE clause, this could as well be a static query that has all possible parameters. So you have the following scenarios:
In case you want to check values that can be everything (negative/nulls/zeros/positive/empty strings/etc), the use of an auxiliary parameter is needed, something like @signifficant_param1, along with the original value of @param1.
[...]
WHERE
(@signifficant_param1=0 or (@param1 is null and field1 is null) or @param1=field1)
AND (@signifficant_param2=0 or (@param2 is null and field2 is null) or @param2=field2)
//etc
[...]
This is the most universal clause I could imagine.
Basically it will verify the @signifficant_param
value. If this parameter should be taken into account, it will be 1, the first part of the condition will be false and the second part (the verification of the parameter) will take place. In the second phase, if @param
is null, then you are looking for all null values of field
, and you can't compare null to null, because they are not equal. Then takes place the verification of regular non-null values match.
If, on the other hand, the values in field
can't be null, or can't be negative, you don't need the @signifficant_param
, because you can make a rule, for example, if @param
is null, then this value is not signifficant (in the previous case, you would have to search all null values instead), you could use the following:
[...]
WHERE
field1=case when @param1 is null then field1 else @param1 end --first way with case statement
and (@param2 is null or field2=@param2) --second way with boolean logic
[...]