我们过去使用的另一种方法是创建一个带有我们想要移动的主键的临时表,并使用while循环。这样,您可以以块状方式执行操作,从而避免了大型事务开销,如果取消操作,则必须回滚。
基本上,您最终要做的是将数据插入到目标表中,例如:insert into tablename (...) select (...) from table name where primary key in (select top 10000 key from temptable)
您需要在第二个结果集中获取前10000条记录,以便从临时表中删除它们,以免再次处理。
另一种方法是使用游标来减少每次处理的记录数。
另一种循环方法是在while循环中执行以下操作:
declare @stop as int
set @stop = (select count(primaryKey) from tableName where primaryKey not in destinstiontable)
while (@stop > 0)
begin transaction
insert into destinationTable (...)
select (...) from sourcetable where primaryKey not in (select primarykey from destinationtable)
commit
set @stop = (select count(primaryKey) from tableName where primaryKey not in destinstiontable)
end
这不是最有效的方法,但它可以工作,并且应该允许您保持事务日志。除非您需要它,还要确保使用no lock关键字,以便在执行此大型移动时不会阻止其他事务(除非您使用BCP或DTS,因为它们要快得多)。
其中一些可能是您最好的选择。使用BCP、DTS或其他批量工具。如果您可以删除索引,将使事情变得更快。