title: Better way of performing dynamic conditional searching in TSQL?
body: <p>We have a large-ish query here that has several params, and for each one, the query only differs by one portion of the <code>where</code> clause, like so:</p>
  
  <p><code>CASE WHEN @IncludeNames = 1 AND @NameFilter IS NULL THEN</code> </p>
  
  <p><code>(SELECT blah FROM blahBlah</code></p>
  
  <pre><code>    INNER JOIN ... 
      INNER JOIN ...
      INNER JOIN ...
      WHERE blahBlah.Id = x.Id)
  </code></pre>
  
  <p><code>WHEN @IncludeNames = 1 AND @NameFilter IS NOT NULL THEN</code></p>
  
  <p><code>(SELECT blah FROM blahBlah</code></p>
  
  <pre><code>    INNER JOIN ... 
      INNER JOIN ...
      INNER JOIN ...
      WHERE blahBlah.Id = x.Id
      AND table2.Id = @NameFilter
  </code></pre>
  
  <p>It goes on like that for several instances, differing only by one condition on the where clause.</p>
  
  <p>Keep in mind this is in the middle of a larger select.</p>
  
  <p>Is there a good way of cleaning this up, without placing it all into one large concatenated sql string and running <code>exec</code> on it, or using something absurd like multiple stored procs per block, as shown here: <a href="http://www.developerfusion.com/article/7305/dynamic-search-conditions-in-tsql/7/" rel="nofollow">http://www.developerfusion.com/article/7305/dynamic-search-conditions-in-tsql/7/</a></p>
  
  <p>Server is SQL Server 2008 R2.  TIA!</p>