--创建临时表 CREATE TABLE #L( ID int IDENTITY(1,1) NOT NULL, Data NVARCHAR(50) primary key(ID) ) --@CurrentYear INT 当前年,@CurrentMonth INT 当前月, --@StartYear INT 起始年,@StartMonth INT起始月 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 --获取最后每一月的最后一天 --SELECT @dt=dateadd(day,-1,dateadd(month,1,rtrim(@StartYear)+'-'+rtrim(@StartMonth)+'-01')) --获取最后每一月的最后一天的最后一秒 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 @StartMonth=@StartMonth+1 END 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 @StartMonth=@StartMonth+1 END END SET @StartYear=@StartYear+1 SET @StartMonth=1 END DECLARE @time varchar(50) DECLARE My_Cursor CURSOR --定义游标 FOR (SELECT Data FROM #L) --查出需要的集合放到游标中 OPEN My_Cursor; --打开游标 FETCH NEXT FROM My_Cursor INTO @time; --读取第一行数据 WHILE @@FETCH_STATUS = 0 BEGIN PRINT @time; --打印数据 INSERT INTO datetimess VALUES (@time) FETCH NEXT FROM My_Cursor INTO @time; --读取下一行数据 END CLOSE My_Cursor; --关闭游标 DEALLOCATE My_Cursor; --释放游标 GO --删除临时表 DROP TABLE #L