日期:2014-05-17 浏览次数:20605 次
create function calcmonth(@dt1 datetime,@dt2 datetime)
returns @re table(id int identity(1,1),yyyy int,MM int)
as
begin
declare @month1 int
declare @year1 int
declare @month2 int
declare @year2 int
declare @count int
select @month1=MONTH(@dt1)
select @year1=YEAR(@dt1)
select @count=datediff(month,@dt1,@dt2)
while @count>=0
begin
insert into @re(yyyy,MM) values(@year1,@month1)
set @count=@count-1
set @month1=@month1+1
if @month1>12
begin
set @month1=1
set @year1=@year1+1
end
end
return
end
GO
--调用方法
Select * from dbo.calcmonth('2010-5-1','2011-3-20')
CREATE table #T1 (nian char(4),yue char(2))
declare @begindate Datetime
SET @begindate='2010-10-5'
declare @enddate datetime
SET @enddate='2011-3-20'
declare @i int,@count int
SET @i=0
SET @count=DATEDIFF(month,@begindate,@enddate)
while @i<=@count
begin
insert INTO #T1
select ltrim(YEAR(@begindate)),right('00'+cast(MONTH(@begindate) as varchar(2)),2)
set @begindate=DATEADD(month,1,@begindate)
set @i=@i+1
end
select * from #T1
DECLARE @start DATETIME='2010-10-05',
@end DATETIME='2011-3-20'
SELECT YEAR(DATEADD(MONTH,number,@start)) AS [nian],
CASE LEN(MONTH(DATEADD(MONTH,number,@start))) WHEN 1
THEN LTRIM(0)+LTRIM(MONTH(DATEADD(MONTH,number,@start)))
ELSE LTRIM(MONTH(DATEADD(MONTH,number,@start)))
END AS [yue]
FROM master..spt_values
WHERE [type]='P'
AND DATEADD(MONTH,number,@start)<=@end
--------------------
nian yue
2010 10
2010 11
2010 12
2011 01
2011 02
2011 03