title: SQL - Rewrite date based query without string manipulation?
body: <p>I have a SQL query that runs on a SQL 2008 R2 server.  It is run on the 1st and the 16th of the month. The query contains the following logic for setting StartDate and EndDate parameters:</p>
  
  <pre><code>DECLARE     @RunDateTime datetime
  DECLARE     @RunDate datetime
  DECLARE     @StartDate datetime
  DECLARE     @EndDate datetime
  DECLARE     @Month int
  DECLARE     @Year int
  DECLARE     @strStartDate varchar(10)
  
  SET     @RunDateTime = GetDate()
  SET     @RunDate = CAST(@RunDateTime AS DATE)
  
  IF                  DATEPART(d, @RunDate) = 16
      BEGIN       
                      SET @StartDate =  DATEADD(d, -15, @RunDate)
                      SET @EndDate = @RunDate
      END
  ELSE
      BEGIN
                      IF      Month(@RunDate) = 1
                              SET @Month = 12
                      ELSE    
                              SET @Month = Month(@RunDate) - 1
  
                      IF      Month(@RunDate) = 1
                              SET @Year = Year(@RunDate) - 1
                      ELSE
                              SET @Year = Year(@RunDate)
  
                      SET @strStartDate = CAST(@Year AS VARCHAR) + CAST(@Month AS VARCHAR) + '16'
                      SET @StartDate = CONVERT(datetime, @strStartDate)
                      SET @EndDate = @RunDate
      END
  </code></pre>
  
  <p>If the query is run on the 16th, we want the date range to be from the 1st to the 15th of the month.  If the query is run on the 1st, we want the date range to be from the 16th to the end of the previous month.</p>
  
  <p>Due to changing requirements at work, we've been told we need to find a way to do this without using any conversion of dates to strings. Is this possible, and does anyone have any idea how it might be done? I am very quickly getting out of my depth here.</p>