title: select first day of previous month from record in sql server
body: <p>I have a table that has a column called <code>StartDateTime</code> that stores datetime values. I need a statement that will return the date of the first day in the previous month of the current record. So, if the stored date is <code>2006-06-17 08:23:42.000</code> the statement would return <code>2006-05-01 00:00:00.000</code> and importantly if the stored date is <code>2006-01-17 08:23:42.000</code> the statement would return <code>2005-11-1 00:00:00.000</code> </p>
  
  <p>If I could use <code>DATEBYPARTS</code> this seems like it would be simple, but unfortunately I can not.
  I tried using </p>
  
  <pre><code>CAST( 
     CAST( Year([StartDateTime]) as varchar(4) ) 
     + '-' + 
     CAST( (Month([StartDateTime])-1) as varchar(2) ) 
     + '-' + 
     CAST( '1' as varchar(2) ) 
  AS DATETIME )
  </code></pre>
  
  <p>but it errors on January 1st dates and gives error "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."</p>