I am trying to implement a sql query for a search and there are a number of fields that I need to be able to search across but they are all optional. I have implemented the query in the following way:
SELECT --<some fields>
FROM --<some tables>
WHERE ((@param1 IS NULL) OR ([FirstName] = @param1))
AND((@param2 IS NULL) OR ([Surname] = @param2))
AND((@param3 IS NULL) OR ([CompanyName] = @param3))
What I am finding though is that now I have about 6 params, even when they are all null, the query takes far too long to execute.
I prefer not to be executing dynamic sql and only adding the sql conditions that are needed based on the parameters. Is there any way that I can optimise this query to make sure that it is not executing all of the conditional logic?
Just as an FYI, I don't think that the speed issue is down to indexes as I have look at the execution plans and it is running of Index Scans rather than Table Scans or Lookups.