这是我快速整理的一些示例代码供您试验。这不使用游标(使用 while 代替),但您也可以这样构建它。您可以进行一些性能优化,但只有您可以判断。YMMV
set nocount on
/* mock up source/dest tables */
declare @src table (id int, value varchar(max));
declare @dest table (id int, value varchar(max));
/* fill source with some data */
declare @rownum int;
set @rownum=0;
while (@rownum<5000) begin
insert into @src select @rownum,'test value ' + CONVERT(varchar(25),@rownum);
select @rownum=@rownum+1;
end
/* laod batched data */
declare @pagesize int;set @pagesize=1000;
declare @rowlow int;set @rowlow=0;
declare @rowmax int;set @rowmax=@pagesize;
declare @ct int;select @ct = COUNT(*) from @src;
declare @id int;
declare @value varchar(max);
while (@rowmax<=@ct) begin
WITH result_set AS (
SELECT ROW_NUMBER() OVER (ORDER BY id) AS [row_number], id,value
FROM @src
) insert into @dest
SELECT id,value FROM result_set
WHERE [row_number] BETWEEN @rowlow AND @rowmax
-- Output
print 'Copied rows ' + convert(varchar(25),@rowlow) + ' to ' + convert(varchar(25),@rowmax)
-- Increment batch counters
select @rowlow=@rowmax+1,@rowmax+=@pagesize;
end
select * from @dest