Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Using CTE:</p> <pre><code>DECLARE @Begin DATETIME DECLARE @End DATETIME SELECT @Begin = '20110101', @End = '20120101' ;WITH ranges(DateFrom, DateTo) AS ( SELECT @Begin, DATEADD(DAY, -1, DATEADD(MONTH, 1, @begin)) UNION ALL SELECT DATEADD(month, 1, DateFrom), DATEADD(DAY, -1, DATEADD(MONTH, 2, DateFrom)) FROM ranges WHERE DateFrom &lt; @End ) SELECT * FROM ranges OPTION(MAXRECURSION 0) </code></pre> <p><strong>And</strong> not using CTE:</p> <pre><code>DECLARE @Begin DATETIME DECLARE @End DATETIME SELECT @Begin = '20110101', @End = '20120101' SELECT DATEADD(MONTH, n.Number, @Begin) DateFrom, DATEADD(day, -1, DATEADD(MONTH, n.Number+1, @Begin)) DateTo FROM master.dbo.spt_values n WHERE n.Number &lt; DATEDIFF(MONTH, @begin, @end) AND n.Type = 'P' </code></pre> <p>If you need to include January 2012 too, use this</p> <pre><code>DECLARE @Begin DATETIME DECLARE @End DATETIME SELECT @Begin = '20110101', @End = '20120101' SELECT DATEADD(MONTH, n.Number, @Begin) DateFrom, DATEADD(day, -1, DATEADD(MONTH, n.Number+1, @Begin)) DateTo FROM master.dbo.spt_values n WHERE n.Number &lt;= DATEDIFF(MONTH, @begin, @end) AND n.Type = 'P' </code></pre> <p>And CTE:</p> <pre><code>DECLARE @Begin DATETIME DECLARE @End DATETIME SELECT @Begin = '20110101', @End = '20120101' ;WITH ranges(DateFrom, DateTo) AS ( SELECT @Begin, DATEADD(DAY, -1, DATEADD(MONTH, 1, @begin)) UNION ALL SELECT DATEADD(month, 1, DateFrom), DATEADD(DAY, -1, DATEADD(MONTH, 2, DateFrom)) FROM ranges WHERE DATEADD(month, 1, DateFrom) &lt; @End ) SELECT * FROM ranges OPTION(MAXRECURSION 0) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload