在SQL Server中一次插入固定数量的行2000
时间:2020-03-06 14:43:24 来源:igfitidea点击:
我想一次将50,000条记录插入sql server数据库2000中。如何做到这一点?
解决方案
我们是说要进行某种测试?
declare @index integer set @index = 0 while @index < 50000 begin insert into table values (x,y,z) set @index = @index + 1 end
但是我希望这不是意思。
如果我们是进行批量插入的最佳方法,请使用"大容量插入"或者类似" bcp"的名称
我们是通过编程方式还是从平面文件从另一个数据库/表插入?
从外部数据源可以使用bcp导入数据。 -b开关允许我们指定批处理大小。
我们可以使用SELECT TOP子句:在MSSQL 2005中,它已得到扩展,允许我们使用变量来指定记录数(旧版本仅允许数字常量)
我们可以尝试这样的事情:
(未经测试,因为目前我无法访问MSSQL2005)
begin declare @n int, @rows int select @rows = count(*) from sourcetable select @n=0 while @n < @rows begin insert into desttable select top 2000 * from sourcetable where id_sourcetable not in (select top (@n) id_sourcetable from sourcetable order by id_sourcetable) order by id_sourcetable select @n=@n+2000 end end
将@rows声明为int
设置@行= 1
而@rows> 0
开始
insert mytable (field1, field2, field3) select top 2000 pa.field1, pa.field2, pa.field3 from table1 pa (nolock) left join mytable ta (nolock)on ta.field2 = pa.feild2 and ta.field3 = pa.field3 and ta.field1 = pa.field1 where ta.field1 is null order by pa.field1
设置@行= @@行数
结尾
这是我们当前在SQL Server 2000的生产环境中使用的代码,其中表和字段名已更改。
使用SQL 2000,我可能会依靠DTS来执行此操作,具体取决于数据所在的位置。我们可以专门告诉DTS批处理提交大小要使用什么。否则,修改版本的SQL 2005批处理解决方案将是不错的选择。我认为我们不能在SQL 2000中将TOP与变量一起使用。