title: If any parameter is present do WHERE if both parameters are null do different WHERE
body: <p>I have a stored procedure that takes in 3 parameters:</p>
  <ul>
  <li>@FKId</li>
  <li>@StartDate</li>
  <li>@EndDate</li>
  </ul>
  <p>I have this query:</p>
  <pre><code>SELECT * 
  FROM Entity
  WHERE [Entity].[FKId] = @FKId
    AND ((@StartDate IS NULL) OR (@StartDate IS NOT NULL AND [Entity].[DateFrom] &gt;= @StartDate))
    AND ((@EndDate IS NULL) OR (@EndDate IS NOT NULL AND [Entity].[DateUntil] &lt;= @EndDate))
  </code></pre>
  <p>I now want to add another part to the where clause when both <code>StartDate</code> and <code>EndDate</code> are both null I want to check if <code>[DateUntil]</code> is then greater than <code>GETDATE()</code> OR IS NULL.</p>
  <p>The query I've tried and not sure why its not working is:</p>
  <pre><code>AND ((@StartDate IS NULL AND @EndDate IS NULL AND ([Entity].[DateUntil] &gt;= GETDATE() OR ([Entity].[DateUntil] IS NULL))
  </code></pre>
  <p>This then seems to remove the FKId part of the clause, so I sectioned that off with brackets so it always executes that part. If the parameters are null both null it works, if both parameters have values it works, but if its a mix then it returns nothing.</p>
  <p>I'm primarily a C# dev so expecting this to just work like an IF statement but its not.</p>
  <p>Any suggestions?</p>