Excel VBA – SQL Server表慢速更新
我正在使用下面的VBA代码将Excel工作表的范围导出到SQL Server表( 此处为原始源 )
Function ExportRangeToSQL(sourceRange As Range, conString As String, tableName As String) As Integer On Error Resume Next Dim con As Object Set con = CreateObject("ADODB.Connection") con.ConnectionString = conString con.Open Dim cmd As Object Set cmd = CreateObject("ADODB.Command") ' Do work within Transaction:' Dim level As Long level = con.BeginTrans cmd.CommandType = 1 ' adCmdText' Dim rst As Object Set rst = CreateObject("ADODB.Recordset") With rst ' Get Column Mapping Information from DB:' Set .ActiveConnection = con .Source = "SELECT TOP 1 * FROM " & tableName .CursorLocation = 3 ' adUseClient' .LockType = 4 ' adLockBatchOptimistic' .CursorType = 0 ' adOpenForwardOnly' .Open ' Column mappings' Dim tableFields(100) As Integer Dim rangeFields(100) As Integer Dim exportFieldsCount As Integer exportFieldsCount = 0 Dim col As Integer Dim index As Integer ' Map range Columns to DB Columns:' For col = 0 To .Fields.Count - 1 index = Application.Match(.Fields(col).Name, sourceRange.Rows(1), 0) If index > 0 Then exportFieldsCount = exportFieldsCount + 1 tableFields(exportFieldsCount) = col rangeFields(exportFieldsCount) = index End If Next If exportFieldsCount = 0 Then ExportRangeToSQL = 1 GoTo ConnectionEnd End If ' Load the Range into the Recordset:' Dim arr As Variant arr = sourceRange.Value Dim row As Long Dim rowCount As Long rowCount = UBound(arr, 1) Dim val As Variant For row = 2 To rowCount .AddNew For col = 1 To exportFieldsCount val = arr(row, rangeFields(col)) If IsEmpty(val) Then Else .Fields(tableFields(col)) = val End If Next Next ' Update the table using the same RecordSet:' .UpdateBatch End With rst.Close Set rst = Nothing ExportRangeToSQL = 0 ConnectionEnd: con.CommitTrans con.Close Set cmd = Nothing Set con = Nothing End Function
基本上它:
- 根据我们希望更新的表创build一个logging集
- 将更新范围的每一列映射到logging集中的一个字段
- 用要上传的数据更新logging集
- 使用
Recordset.UpdateBatch
一次更新表。
但是,我发现这是不可思议的缓慢(对于1000-2000条logging),并且写入单独的插入语句要快得多(尽pipe不是很漂亮)。
任何想法如何使这个更快?
请更改以下这行代码:
.CursorType = 0 ' adOpenForwardOnly'
至
.CursorType = 4 ' adOpenStatic - could also use adOpenKeyset
因为您的游标types未针对更新操作进行优化。
请参阅MSDN参考资料