如何取得一个时间段的每个月
要求列出一段时间里的年份+月份
declare @strdate datetime,
@enddate datetime
set @strdate = '2012-11-20' --会计期间为 每个月20日起至次月19日
set @enddate = '2013-03-19'
select @strdate A, @enddate B
ALTER function generateTimeV2
(
@begin_date datetime,
@end_date datetime
)
returns @t table(date VARCHAR(8))
as
begin
insert into @t
select left(CONVERT(CHAR(30),dateadd(dd,number,@begin_date)),4)+SUBSTRING(CONVERT(CHAR(30),dateadd(dd,number,@begin_date)),6,2) AS date
from master..spt_values
where type='p' and dateadd(dd,number,@begin_date)<=@end_date
return
end
--测试示例
select * from dbo.generateTimeV2('2012-11-20','2013-03-19')
declare @strdate datetime,@enddate datetime
set @strdate = '2012-11-20' --会计期间为 每个月20日起至次月19日
set @enddate = '2013-03-19'
;WITH a1 (date,ym) AS
(
SELECT DATEADD(mm,1,@strdate),CONVERT(CHAR(6),DATEADD(mm,1,@strdate),112)
UNION ALL
SELECT DATEADD(mm,1,date),CONVERT(CHAR(6),DATEADD(mm,1,date),112) FROM a1
WHERE date<=@enddate
)
SELECT ym FROM a1