查询某一时间段内的所有月份,可以代码如下:
--方法一: declare @date1 varchar(10), @date2 varchar(10) set @date1 = '2010-01-01' set @date2 = '2010-12-01' select convert(varchar(7),cast(ltrim(year(@date1)) + '-'+ ltrim(number) + '-01' as datetime),120) as yuefen from master..spt_values where type = 'p' and number between month(@date1) and month(@date2) --方法二: declare @dt1 as datetime declare @dt2 as datetime set @dt1 = '2008-01-01' set @dt2 = '2009-01-01' --使用一个临时表 select top 8000 identity(int,0,1) as id into # from syscolumns a,syscolumns b select yuefen = convert(varchar(7),dateadd(mm , m.id , @dt1 ),120) from # m where convert(varchar(7),dateadd(mm , m.id , @dt1 ),120) <= convert(varchar(7),@dt2,120) drop table #
--方法三:某段时间内的年份,如果要月份将year改为month declare @years int, @begin datetime, --时间段开始时间 @end datetime --时间段结束时间 set @begin = '2017-01-01'; set @end = '2017-12-31'; set @years=DATEDIFF(year,@begin,@end) select convert(varchar(4),DATEADD(year,number,@begin) ,120) AS months from master.dbo.spt_values where type='p' AND number<=@years
以上两种方式都可以查询出时间段内包含的所有月份。