MS Access Insert Into Slow for Large Recordset (VBA)

前端 未结 2 853
悲&欢浪女
悲&欢浪女 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
    

提交回复
热议问题