MS Access Insert Into Slow for Large Recordset (VBA)

前端 未结 2 851
悲&欢浪女
悲&欢浪女 2021-01-24 16:16

I have a section of code which creates a new table and then attempts to copy the record set values into the table. The only problem is this it is quite slow and access shows the

相关标签:
2条回答
  • 2021-01-24 16:34

    Yes, use DAO. So much faster. This example copies to the same table, but you can easily modify it so copy between two tables:

    Public Sub CopyRecords()
    
      Dim rstSource   As DAO.Recordset
      Dim rstInsert   As DAO.Recordset
      Dim fld         As DAO.Field
      Dim strSQL      As String
      Dim lngLoop     As Long
      Dim lngCount    As Long
    
      strSQL = "SELECT * FROM tblStatus WHERE Location = '" & _
                    "DEFx" & "' Order by Total"
    
      Set rstInsert = CurrentDb.OpenRecordset(strSQL)
      Set rstSource = rstInsert.Clone
      With rstSource
        lngCount = .RecordCount
        For lngLoop = 1 To lngCount
          With rstInsert
            .AddNew
              For Each fld In rstSource.Fields
                With fld
                  If .Attributes And dbAutoIncrField Then
                    ' Skip Autonumber or GUID field.
                  ElseIf .Name = "Total" Then
                    ' Insert default value.
                    rstInsert.Fields(.Name).Value = 0
                  ElseIf .Name = "PROCESSED_IND" Then
                    rstInsert.Fields(.Name).Value = vbNullString
                  Else
                    ' Copy field content.
                    rstInsert.Fields(.Name).Value = .Value
                  End If
                End With
              Next
            .Update
          End With
          .MoveNext
        Next
        rstInsert.Close
        .Close
      End With
    
      Set rstInsert = Nothing
      Set rstSource = Nothing
    
    End Sub
    
    0 讨论(0)
  • 2021-01-24 16:40

    For multiple inserts in a loop, don't use SQL INSERT statements. Instead use a DAO.Recordset with .AddNew.

    See this answer: https://stackoverflow.com/a/33025620/3820271

    As positive side effects, your code will become better readable and you don't have to deal with the multiple formats for different data types.

    For Each field In RecordSet1.Fields
         rsTarget(field.Name) = field.Value
    Next field
    
    0 讨论(0)
提交回复
热议问题