title: Using an IF statement to decide which where clause to execute
body: <p>I'm working in SQL Server 2008. I'm trying to decide which <code>WHERE</code> statement to run based on an <code>IF</code> statement. That may not be the correct way to go about this, I'm honestly not sure. Here is my code so far:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>SELECT A.[ArTrnDetail].[Invoice]
        ,cast(A.[ArTrnDetail].[InvoiceDate] AS DATE) AS InvoiceDate
        ,A.[ArTrnDetail].[Branch]
        ,A.[ArTrnDetail].[Salesperson]
        ,rtrim(A.[ArTrnDetail].[Customer]) AS Customer
        ,rtrim(A.[ArTrnDetail].[StockCode]) AS StockCode
        ,A.[ArTrnDetail].[QtyInvoiced]
        ,A.[ArTrnDetail].[NetSalesValue]
        ,A.[ArTrnDetail].[SalesOrder]
        ,rtrim(A.[ArTrnDetail].[CustomerPoNumber]) AS CustomerPO
        ,cast(B.[EarliestSalesSeries].[InvoiceDate] as DATE) AS EarliestDate
        ,DATEADD(year, 1, B.[EarliestSalesSeries].[InvoiceDate]) as LatestDate
        ,A.[InvMaster].[Description]
        ,LEFT(A.[InvMaster].[UserField2], 3) AS SalesSeries
        ,DATEDIFF(DAY,B.[EarliestSalesSeries].[InvoiceDate], @enddate) as DateDifference   
      FROM A.[ArTrnDetail]
      JOIN A.[InvMaster] ON A.[ArTrnDetail].StockCode
      = A.[InvMaster].[StockCode]
      JOIN B.[EarliestSalesSeries] ON A.[InvMaster].[UserField2]
      = B.[EarliestSalesSeries].SalesSeries</code></pre>
  </div>
  </div>
  </p>
  
  <p>I've defined @firstYearDay in the beginning of the code, before SELECT.    </p>
  
  <p>I need this to happen:</p>
  
  <p>IF LatestDate > @enddate then run this where clause:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>   WHERE (A.[ArTrnDetail].[InvoiceDate] between @firstYearDay and @enddate)
   AND (DATEDIFF(YEAR,B.[EarliestSalesSeries].[InvoiceDate], @enddate) &lt; 1)</code></pre>
  </div>
  </div>
  </p>
  
  <p>ELSE IF LatestDate &lt; @enddate then run this where clause:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>   WHERE (A.[ArTrnDetail].[InvoiceDate] between @firstYearDay and LatestDate)
   AND (DATEDIFF(YEAR, B.[EarliestSalesSeries].[InvoiceDate], @firstYearDay) &lt; 1)</code></pre>
  </div>
  </div>
  </p>
  
  <p>If you need more info, let me know. I'm new to stackoverflow so please just ask! Thanks for the help.</p>