嗯......敢说这可以改进,但作为一个粗略的'n'准备好(假设ms-sql)
create table #results (ID varchar(10), Month int, Year int);
declare @ID varchar(10);
declare @StartDate datetime;
declare @EndDate datetime;
declare myCursor cursor for select [ID], [StartDate],[EndDate] from ItemsInUse;
open myCursor;
delete from #results;
fetch next from myCursor into @ID, @StartDate, @EndDate;
declare @tempDate datetime;
while @@FETCH_STATUS = 0
begin
set @tempdate = CAST( CAST(year(@StartDate) AS varchar) + '-' + CAST(MONTH(@StartDate) AS varchar) + '-' + CAST(1 AS varchar) AS DATETIME);
while @tempDate < @EndDate
begin
insert into #results values (@ID, MONTH(@tempDate), YEAR(@tempDate));
set @tempDate = DATEADD(month,1,@tempdate);
end
fetch next from myCursor into @ID, @StartDate, @EndDate;
end
close myCursor;
deallocate myCursor;
select * from #results;
drop table #results;