SQL Server 2008:批量插入表

SQL Server 2008:批量插入表

问题描述:

我有一个链接服务器(Sybase)在SQL Server中设置,我需要从中绘制数据。 Sybase服务器位于世界的另一端,连接性非常低劣。我想以可管理的批次将数据插入到其中一个SQL Server表中(例如,一次有1000个记录)。即我想要做;SQL Server 2008:批量插入表

INSERT IN [SQLServerTable] ([field]) 
SELECT [field] from [LinkedServer].[DbName].[dbo].[SybaseTable] 

但我想一次获取1000条记录并插入它们。

感谢
卡尔

我通常使用Python与pyodbc模块,这样对SQL Server执行批处理。看一看,看看它是否是一种选择,如果是的话,我可以给你提供一个例子。

您将需要修改大量代码以适应您的特定情况,但是您应该能够遵循逻辑。您可以注释掉cnxn.commit()行来回滚事务,直到您完成所有工作。

import pyodbc 

#This is an MS SQL2008 connection string 
conn='DRIVER={SQL Server};SERVER=SERVERNAME;DATABASE=DBNAME;UID=USERNAME;PWD=PWD' 

cnxn=pyodbc.connect(conn) 
cursor=cnxn.cursor() 

rowCount=cursor.execute('SELECT Count(*) from RemoteTable').fetchone()[0] 

cnxn.close() 

count=0 
lastID=0 


while count<rowCount: 
    #You may want to close the previous connection and start a new one in this loop. Otherwise 
    #the connection will be open the entire time defeating the purpose of performing the transactions in batches. 

    cnxn=pyodbc.connect(conn) 
    cursor=cnxn.cursor() 

    rows=cursor.execute('SELECT TOP 1000 ID, Field1, Field2 FROM INC WHERE ((ID > %s)) ' % (lastID)).fetchall() 

    for row in rows: 
     cursor.execute('INSERT INTO LOCALTABLE (FIELD1, FIELD2) VALUES (%s, %s)' % (row.Field1, row.Field2)) 


    cnxn.commit() 
    cnxn.close() 

    #The [0] assumes the id is the first field in the select statement. 
    lastID=rows[len(rows)-1][0] 
    count+=len(rows) 

    #Pause after each insert to see if the user wants to continue. 
    raw_input("%s down, %s to go! Press enter to continue." % (count, rowCount-count)) 
+0

这可以工作是的。一个例子,将不胜感激。卡尔 – Karl 2011-02-04 08:41:37