我的任务是将数据从另一个表中批量插入表中,因为原始表包含超过400万条记录,并且会减慢其他进程的速度。
需要注意的是 - 我知道'插入select * from ..'语法
所以我尝试了以下程序,有人可以告诉我它是否正确。因为我没有看到while循环与限制和偏移一起使用。
create PROCEDURE [dbo].[sp_name] as
-- Add the parameters for the stored procedure here
BEGIN
DECLARE @value INT;
declare @count int;
SET @value = 0;
set @count=(select count(1) from new_table);
select @count;
WHILE @value <1
begin
insert into new_table
select *,0 from old_table where error=1
order by id offset @count rows fetch next 1000 rows only
SET @value = @value + 1;
end;
END;
存储过程中的名称仅用于表示。
答案 0 :(得分:0)
如果表在批次结束前结束,则WHILE
循环不会终止。
此外,您可能希望键入批次的开始和结束时间为id
值,而不是纯行数。
这种批量处理方法会更加强大:
DECLARE @rowcount INT;
SET @rowcount = 1;
DECLARE @value INT;
SET @value = 0;
DECLARE @count INT;
SET @count=(select count(1) from new_table);
DECLARE @batchstart INT;
SET @batchstart = -1;
IF @count <= 0 THEN
SELECT MAX(id) FROM new_table INTO @batchstart;
END IF
/* now @batchstart holds the largest id value already in new_table */
WHILE @value <1 AND @rowcount > 0
BEGIN
INSERT into new_table
SELECT *,0 from old_table
WHERE id > @batchstart
AND error = 1
ORDER BY id
FETCH NEXT 1000 ROWS ONLY;
/* here we fetch the number of rows actually processed.
* if it's zero, no more rows to process from old_table */
SELECT ROW_COUNT() INTO @rowcount;
SET @value = @value + 1;
/* find out where the next batch, if any, should start */
SELECT MAX(id) FROM new_table INTO @batchstart;
END;