title: SQL function for last 12 months
body: <p>I am looking for a SQL-function that gives the last 12 months with Start Date and End Date. Say you pick 10.Dec, it will give a result in: </p>
  
  <pre><code> - StartDate   --   EndDate 
   - 2013-11-01  -  2013-11-30
   - 2013-10-01  -  2013-10-31
   - 2013-09-01  -  2013-09-30 
  </code></pre>
  
  <p>and so it goes for the last 12 months.</p>
  
  <p>I tried modifying an old function we had, but I got totally off and confused in the end. </p>
  
  <pre><code>ALTER FUNCTION [dbo].[Last12Months](@Date date) RETURNS TABLE 
  AS  
  Return
  ( 
  with cte as (
  SELECT DATEADD(mm, DATEDIFF(mm, 01, @Date), 01) AS Start,
         DATEADD(mm, DATEDIFF(mm, -12, @Date), -12) AS EndDate
   union all
  select Start - 1, EndDate - 1 from cte
  where Start &gt;= @Date )
  select CAST(Start as DATE) StartDate, CAST(EndDate as DATE) EndDate from cte)
  </code></pre>
  
  <p>Runned it like this: </p>
  
  <pre><code>select * from dbo.Last12Months ('2013-12-10')
  </code></pre>
  
  <p>and got: </p>
  
  <pre><code> - StartDate   -  EndDate 
   - 2013-12-02  -  2013-12-20
  </code></pre>
  
  <p>Anyone know what to do? </p>