2011-02-01 2 views
1

데이터를 그릴 필요가있는 SQL Server에 연결된 서버 (Sybase)를 설치했습니다. Sybase 서버는 세계의 다른쪽에 위치하며 연결성은 매우 엉망입니다. 관리 가능한 배치 (예 : 한 번에 1000 개의 레코드)로 SQL Server 테이블 중 하나에 데이터를 삽입하고 싶습니다. 나는 내가하고 싶어한다.SQL Server 2008 : 일괄 처리 테이블에 삽입

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

하지만 한 번에 1000 개의 레코드를 가져 와서 삽입하고 싶습니다.

감사

답변

1

나는 일반적으로 SQL 서버에 대해 다음과 같이 일괄 적으로 수행 할 수 pyodbc 모듈과 파이썬을 사용합니다. 한 번 살펴보고 옵션인지 확인하십시오. 그렇다면 예제를 제공 할 수 있습니다.

특정 상황에 맞게이 코드를 많이 수정해야하지만 논리를 따라야합니다. 모든 것이 작동 할 때까지 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