--创建存储过程 CREATE PROCEDURE TransferToHistory AS BEGIN --不返回计数 SET NOCOUNT ON; --开始捕捉异常 BEGIN TRY -- 声明配置表变量 DECLARE @config TABLE (id NVARCHAR(5)); --创建临时A表 CREATE TABLE #temp(id INT,t_a VARCHAR(15),t_b INT,......); -- 将配置表中的数据插入到配置表变量中 INSERT INTO @config(id) SELECT id FROM config ORDER BY id; -- 声明变量 DECLARE @sql NVARCHAR(MAX),@id NVARCHAR(5); --循环配置表 WHILE EXISTS(SELECT id FROM @config) BEGIN --将条件赋值给变量中 SELECT @id = id FROM @config ORDER BY id; --初始化临时表插入500条 SET @sql ='SELECT TOP 500 id,a,b FROM A_'+ @id +' WITH(NOLOCK) WHERE time <= CONVERT(varchar(10),DATEADD(MONTH,-2,GETDATE()),112) ORDER BY id;'; INSERT INTO #temp(id,t_a,t_b) EXEC (@sql); --判断临时表是否存在数据 WHILE (SELECT COUNT(1) FROM #temp)>0 BEGIN --将临时表数据插入到B表并删除A表数据和临时表数据 SET @sql='INSERT INTO history(type_id,t_a,t_b) SELECT type_id=' + @id + ',t_a,t_b FROM #temp; DELETE A FROM A_' + @id + ' AS A INNER JOIN #temp AS B ON A.id=B.id; DELETE #temp;' EXEC (@sql); --如果A表存在数据继续插入500条到临时表 SET @sql ='SELECT TOP 500 id,a,b FROM A_'+ @id +' WITH(NOLOCK) WHERE time <= CONVERT(varchar(10),DATEADD(MONTH,-2,GETDATE()),112) ORDER BY id;'; INSERT INTO #temp(id,t_a,t_b) EXEC (@sql); END --该条件已全部转完从临时配置表删除 DELETE FROM @config WHERE id=@id; END --使用完删除临时表 DROP TABLE #temp; END TRY-----------结束捕捉异常 BEGIN CATCH------------有异常被捕获 DROP TABLE #temp; SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage END CATCH--------结束异常处理 END