如何将“整个”DAO记录集插入到具有VBA的表中

时间:2011-07-27 10:43:40

标签: ms-access vba ms-access-2007 access-vba dao

我有一个DAO记录集,可以很好地创建,我可以将记录从集合转移到表中,这是逐行完成的并且运行良好但是我一次传输大量数据所以这可以采取很长一段时间。

有没有办法一次性转移整个记录集,而不是逐行转移

请参阅下文,了解当前正在使用的代码 -

Dim SendE1 As DAO.Recordset

Set SendE1 = CurrentDb.OpenRecordset("SELECT TBL_ImportTable.* FROM TBL_ImportTable", dbOpenDynaset)

SendE1.MoveLast

Do Until SendE1.EOF

sqlinsert = "INSERT INTO TBL_E1Jobs (StartDate, StartTime, EndDate, EndTime, Location, UserID, WorkStationID, DocumentNumber, E1Shift, OperSeq, Facility, AdjustedforShifts, WeekNum)" & _
" VALUES ('" & SendE1("StartDate") & "', '" & SendE1("StartTime") & "', '" & SendE1("EndDate") & "', '" & SendE1("EndTime") & "', '" & SendE1("Location") & "', '" & SendE1("UserID") & "', '" & SendE1("WorkstationID") & "', '" & SendE1("DocumentNumber") & "', '" & SendE1("E1Shift") & "', '" & SendE1("OperSeq") & "', '" & SendE1("Facility") & "', '" & SendE1("AdjustedforShifts") & "', '" & SendE1("WeekNum") & "') "

DoCmd.RunSQL (sqlinsert)

SendE1.MoveNext

Loop


SendE1.Close
Set SendE1 = Nothing

2 个答案:

答案 0 :(得分:7)

@cularis是正确的。正确的方法是在SQL查询中。在阅读了他的回答后,您可以采取一些步骤来避免删除未复制的数据:

Dim db As DAO.Database, RecCount As Long

'Get the total number of records in your import table to compare later
RecCount = DCount("*", "TBL_ImportTable")

'This line is IMPORTANT! each time you call CurrentDb a new db object is returned
'  that would cause problems for us later 
Set db = CurrentDb

'Add the records, being sure to use our db object, not CurrentDb
db.Execute "INSERT INTO TBL_E1Jobs (StartDate, StartTime, ..., WeekNum) " & _
           "SELECT StartDate, StartTime, ..., WeekNum " & _
           "FROM TBL_ImportTable", dbFailOnError

'db.RecordsAffected now contains the number of records that were inserted above
'  since CurrentDb returns a new db object, CurrentDb.RecordsAffected always = 0
If RecCount = db.RecordsAffected Then
    db.Execute "DELETE * FROM TBL_ImportTable", dbFailOnError
End If

请注意,如果您在链接的ODBC表上运行这些查询,则需要包含dbSeeChanges选项(即dbFailOnError + dbSeeChanges)。

答案 1 :(得分:2)

不是DAO,而是SQL解决方案,可以满足您的需求:

INSERT INTO TBL_E1Jobs  (StartDate, StartTime, EndDate ...) 
SELECT StartDate, StartTime, EndDate ... FROM TBL_ImportTable

INSERT INTO ... SELECT MSDN