获得启动开始日期和结束日期之间一个月

问题描述:

我想选择的日期之间只有一个月的开始日期的日期获得启动开始日期和结束日期之间一个月

例如:

start date = 2012 -05-01 
end date = 2013-04-01

我想这样

 
    Dates : 
    2012 -05-01 
    2012 -06-01 
    2012 -07-01 ..... 
    2013 -01-01 ..... 
    2012 -05-01
+0

看看这个:http://stackoverflow.com/questions/1520789/how-can-i-select-the-first-day-of-a-month-in-sql – 2013-04-09 13:49:23

+0

这个问题没有显示任何研究努力。 **做你的作业很重要**。告诉我们你发现了什么,***为什么它不符合你的需求。这表明你已经花时间去尝试帮助你自己了,它使我们避免重申明显的答案,最重要的是它可以帮助你得到更具体和相关的答案。 [FAQ](http://stackoverflow.com/questions/how-to-ask)。 – Kermit 2013-04-09 13:49:58

CTE将做诡计

Declare @beginDt SmallDatetime = '13 Jan 2012' 
    Declare @endDt SmallDatetime = '2 Apr 2013'; 
    With MonthList(aMon) 
     As 
     (Select DateAdd(month, datediff(month, 0, @beginDt), 31) 
     Union All 
     Select DateAdd(month, 1, aMon) From MonthList 
     Where DateAdd(month, 1, aMon) < @endDt) 
     Select aMon from MonthList 
+0

请注意CTE的最大递归。使用此代码无法生成9年的数据。 – 2016-04-21 07:04:24

首先,create a calendar table。然后,你可以写一个简单的查询:

select [Date] 
from dbo.Calendar 
where IsFirstDayOfMonth = 1 and [Date] between '20120501' and '20130401' 

这个查询比使用基于函数的解决方案和日历表,可以使用更清楚有许多其他用途了。