I am trying to batch inserting rows from one table to another.
DECLARE @batch INT = 10000;
WHILE @batch > 0
BEGIN
BEGIN TRANSACTION
INSERT into table2
select top (@batch) *
FROM table1
SET @batch = @@ROWCOUNT
COMMIT TRANSACTION
END
It runs on the first 10,000 and inserts them. Then i get error message "Cannot insert duplicate key" which its trying to insert the same primary key so i assume its trying to repeat the same batch. What logic am i missing here to loop through the batches? Probably something simple but i cant figure it out.
Can anyone help? thanks
3条答案
按热度按时间bkkx9g8r1#
Your code keeps inserting the same rows. You can avoid it by "paginating" your inserts:
eqoofvh92#
You need some way to eliminate existing rows. You seem to have a primary key, so:
0wi1tuuw3#
How about using the designated set of keywords for this problem : OFFSET - FETCH