We have many "search stored procedures" that take multiple nullable parameters for searching rows of data in different tables. They're usually built like this:
SELECT *
FROM Table1 T1
INNER JOIN Table2 T2
ON T2.something = T1.something
WHERE (@parameter1 IS NULL OR T1.Column1 = @parameter1)
AND (@parameter2 IS NULL OR T2.Column2 = @parameter2)
AND (@parameter3 IS NULL OR T1.Column3 LIKE '%' + @parameter3 + '%')
AND (@parameter4 IS NULL OR T2.Column4 LIKE '%' + @parameter4 + '%')
AND (@parameter5 IS NULL OR T1.Column5 = @parameter5)
This can go on for up to 30-40 parameters and what we've noticed is even if only parameter1 is provided, the execution plan goes through index scans of the other tables which can slow down the query significantly (few seconds). Tests show us that keeping only the first line from the WHERE statement makes the query instant.
I've read that shortcuiting is not possible, but are there work around or ways to construct queries that would possibly be more efficient?
We currently work around this problem by having different versions of the same SELECT/FROM/JOINS but with different set of parameters in the WHERE clause and depending on which parameters are passed we choose the proper select statement to go through. This is long, messy and hard to maintain.