title: Stored Procedure with conditional results
body: <p>I want to write a stored procedure that works something like this:</p>
  
  <pre><code>SELECT * from T where T.A = @a and T.B = @b
  </code></pre>
  
  <p>if that returns rows, return those rows, if not, return</p>
  
  <pre><code>SELECT * from T where T.A = @a and T.B IS NULL
  </code></pre>
  
  <p><strong>Edit:</strong></p>
  
  <p>It feels that there should be a way to create a procedure such that it runs the first query <strong>once</strong> and runs the second query <strong>only if necessary</strong>.</p>
  
  <p>End Edit.</p>
  
  <p>The best I could manage was the follow, which (in theory) runs the first query twice, unless maybe its cached:</p>
  
  <pre><code>IF EXISTS (SELECT * from T where T.A = @a and T.B = @b) THEN
      SELECT * from T where T.A = @a and T.B = @b
  ELSE
      SELECT * from T where T.A = @a and T.B IS NULL
  </code></pre>
  
  <p>For what its worth, this is in Microsoft SQL Server 2008</p>