We have a large-ish query here that has several params, and for each one, the query only differs by one portion of the where clause, like so:
CASE WHEN @IncludeNames = 1 AND @NameFilter IS NULL THEN
(SELECT blah FROM blahBlah
INNER JOIN ...
INNER JOIN ...
INNER JOIN ...
WHERE blahBlah.Id = x.Id)
WHEN @IncludeNames = 1 AND @NameFilter IS NOT NULL THEN
(SELECT blah FROM blahBlah
INNER JOIN ...
INNER JOIN ...
INNER JOIN ...
WHERE blahBlah.Id = x.Id
AND table2.Id = @NameFilter
It goes on like that for several instances, differing only by one condition on the where clause.
Keep in mind this is in the middle of a larger select.
Is there a good way of cleaning this up, without placing it all into one large concatenated sql string and running exec on it, or using something absurd like multiple stored procs per block, as shown here: http://www.developerfusion.com/article/7305/dynamic-search-conditions-in-tsql/7/
Server is SQL Server 2008 R2. TIA!
Try setting up your query with an option of all or specific values for each clause e.g.
This should allow you to concatenate your clauses into a single select statement. Each parameter may apply a filter or have no effect (if set to the default such as null, empty string or -1).