I am trying to collect specific data from a series of tables in a SQL Server database and combine them together in a single table in Access using VBA.
I created a recordset in Access using a query that combines all the data using multiple UNION ALL statements. My initial approach was to iterate through the recordset with something like:
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim SQL As String
cnn.Open "Driver={SQL Server};Server=" + SQLServerNameStr + ";Database=" + DBNameStr + ";Trusted_Connection=Yes"
SQL = "SELECT A, B, C FROM TableA UNION ALL SELECT D, E, F FROM TableB UNION ALL ..." // etc., etc., etc.
rs.Open SQL, cnn, adOpenForwardOnly
While Not rs.EOF
CurrentDB().Execute ("INSERT INTO AccessTable VALUES ('" & rs("FieldA") & "', '" & rs("FieldB") & "', '" & rs("FieldC") &"')")
rs.MoveNext
Wend
This all works, however, it is excruciatingly slow for approximately 20,000 records. I am sure there is a better way ... probably by building the INSERT into the main query, however, I cannot wrap my head around how to do this when the data source is on a connection to SQL Server and the destination in the current database.
Any suggestions would be greatly appreciated.
Try using DoCmd.TransferDatabase
* to transfer data from a SQL Server view, that queries the data the way you need it, into an Access table.
DoCmd.TransferDatabase acImport, "ODBC Database", _
"Driver={SQL Server};Server=" & SQLServerNameStr & ";Database=" & DBNameStr & _
";Trusted_Connection=Yes", acTable, "SomeSqlServerView", "AccessTable"
Hopefully the transfer database method does a good job of managing insertions and speeds up the import process.
*Changed my answer since batch updates don't work with Access 2010 as a data destination.
I haven't used native tables so much, but I suspect the issue is related to inserting one at a time.
You might want to try doing the insert through SQL and doing 50 rows at a time or so.
Why not try doing an Insert query instead creating a recordset? See this question: How to insert "Entire" DAO recordset into a table with VBA
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.