I'm trying to construct a simple query that will allow the user to filter a list of clients based on demographic information. It seems to me that LIKE
would be the simplest solution, for instance:
SELECT D.Name
FROM demographics D
WHERE D.City LIKE @cityVar
AND D.Sex LIKE @sexVar
AND D.Age LIKE @ageVar
...
Variables are passed into the query using combo boxes; therefore if the user decides not to filter based on any given parameter, I simply pass '%'
to the variable, effectively escaping that line in the WHERE
clause.
However, this does not work if I would like to return rows containing NULL
values in filtered fields. For instance, if D.Employer
has a value of NULL
, the client is unemployed; but passing '%'
to @employedVar
(meaning that the user would like to return both employed and unemployed clients) ignores all rows where D.Employer
is NULL
.
How would I construct the logic of the WHERE
clause in order to account for a large number of parameters while still allowing the user to escape filtering on any given parameter, all the while including NULL
values when appropriate?