-- Create Table # L (ID int identity (1,1) not null, data nvarchar (50) primary key (ID) [email protected] int current year, @ currentmonth int current month, [email protected] int start year, @ startmonth int start month declare @ currentyear int, @ currentmonth int, @ startyear int, @ startmonth int set @ startyear = 2012 set @ startmonth = 1 Set @ currentyear = datepart (year, getdate () set @ currentmonth = datepart (month, getdate ()) declare @ DT datetime, @ DTS nvarchar (50) while @ startyear <@ currentyear + 1 begin if (@ startyear <> @ currentyear) begin while @ startmonth <13 begin -- get the last day of every month -- select @ dt = dateadd (day,-1, dateadd (month, 1, rtrim (@ startyear) + '-' + rtrim (@ startmonth) + '-01') -- Obtain the last second of the last day of June 1, January select @ dt = dateadd (second,-1, dateadd (day,-1, rtrim (@ startyear) + '-' + rtrim (@ startmonth) + '-01 ')) print @ DT set @ DTS = convert (nvarchar (20), @ DT, 120) insert into # l values (@ DTS) set @ [email protected] + 1 end else begin while @ startmonth <@ currentmonth + 1 begin select @ dt = dateadd (second,-1, dateadd (day,-1, rtrim (@ startyear) + '-' + rtrim (@ startmonth) + '-01') print @ DT set @ DTS = convert (nvarchar (20), @ DT, 120) insert into # l values (@ DTS) set @ [email protected] + 1 end set @ [email protected] + 1 Set @ startmonth = 1 end declare @ time varchar (50) declare my_cursor cursor -- Define the cursor for (Select data from # l) -- find the desired set and put it in the cursor open my_cursor; -- open the cursor fetch next from my_cursor into @ time; -- read the first row of data while @ fetch_status = 0 begin print @ time; -- print the data insert into datetimess values (@ time) Fetch next from my_cursor into @ time; -- read the next row of Data endclose my_cursor; -- close the cursor deallocate my_cursor; -- release the cursor go -- delete the temporary table drop table # l
Obtain the last day of each month and use the cursor to exist in a new table.