2011-02-01 26 views
1

SQL Serverにリンクサーバー(Sybase)を設定してデータを取得する必要があります。 Sybaseサーバは世界の反対側に位置しており、接続はかなり面倒です。 SQL Serverテーブルの1つに、管理可能なバッチ(一度に1000レコードなど)でデータを挿入したいと考えています。私はしたい。SQL Server 2008:バッチでテーブルに挿入

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

しかし、私は一度に1000レコードを取り出して挿入したいと思います。

おかげで、私は通常、SQLサーバーに対して、このようなバッチを実行するためにpyodbcモジュールでのpythonを使用
カール

答えて

1

。見て、それがオプションであるかどうかを確認してください、もし私があなたに例を提供することができます。

特定の状況に合わせて多くのコードを変更する必要がありますが、ロジックに従うことができます。 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

関連する問題