如何在Access中为多个列提高批量INSERT到ODBC链接表的性能?

时间:2015-09-24 11:17:12

标签: sql-server tsql ms-access odbc ms-access-2010

此问题基于以下问题:How to increase performance for bulk INSERTs to ODBC linked tables in Access?

我还要进一步了解上面的链接主题,因为我没有足够的分数来评论这个主题,所以我在这里创建了我的问题。

来自Gord Thompson的优秀答案,他在上面的链接中提供了以下代码。

Sub PtqTest()
Dim cdb As DAO.Database, rst As DAO.Recordset
Dim t0 As Single, i As Long, valueList As String, separator As String

t0 = Timer
Set cdb = CurrentDb
Set rst = cdb.OpenRecordset("SELECT MPO_REFERENCE FROM tblTempSmartSSP", dbOpenSnapshot)
i = 0
valueList = ""
separator = ""
Do Until rst.EOF
    i = i + 1
    valueList = valueList & separator & "(" & rst!MPO_REFERENCE & ")"
    If i = 1 Then
        separator = ","
    End If
    If i = 1000 Then
        SendInsert valueList
        i = 0
        valueList = ""
        separator = ""
    End If
    rst.MoveNext
Loop
If i > 0 Then
    SendInsert valueList
End If
rst.Close
Set rst = Nothing
Set cdb = Nothing
Debug.Print "Elapsed time " & Format(Timer - t0, "0.0") & " seconds."
End Sub

Sub SendInsert(valueList As String)
Dim cdb As DAO.Database, qdf As DAO.QueryDef

Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
qdf.Connect = cdb.TableDefs("METER_DATA").Connect
qdf.ReturnsRecords = False
qdf.sql = "INSERT INTO METER_DATA (MPO_REFERENCE) VALUES " & valueList
qdf.Execute dbFailOnError
Set qdf = Nothing
Set cdb = Nothing
End Sub

我的问题是如果我想在插入过程中包含多个列?例如,除了MPO_REFERENCE之外,我还有一个名为NEW_COLUMN的列要插入METER_DATA (来自sql server的odbc链接表),我尝试对上面代码中的某些行进行修改但是失败了。对不起,我是SQL和VB的新手,非常感谢有人可以提供帮助。谢谢。

    ...
    Set rst = cdb.OpenRecordset("SELECT MPO_REFERENCE,NEW_COLUMN FROM tblTempSmartSSP", dbOpenSnapshot)
    ...
    ...
        valueList = valueList & separator & "(" & rst!MPO_REFERENCE & "," & rst!NEW_COLUMN & ")"

    ...
    ...
    qdf.sql = "INSERT INTO METER_DATA (MPO_REFERENCE,NEW_COLUMN) VALUES " & valueList

    ...

1 个答案:

答案 0 :(得分:1)

基本上,你有了主意,代码是正确的。

但是你必须考虑其他一些事情:

  1. 如果rst!NEW_COLUMN为空,则将空字符串传递给SQL命令,这将导致错误。

    e.g。导致SQL-string的错误:

    INSERT INTO METER_DATA (MPO_REFERENCE,NEW_COLUMN) VALUES (3, )

    在构建SQL字符串

  2. 之前检查NEW_COLUMN是否为空
  3. 如果NEW_COLUMN是字符串值,则必须在单引号之间设置。这看起来像是:

    valueList = valueList & separator & "(" & rst!MPO_REFERENCE _ & ",'" & rst!NEW_COLUMN & "')"

  4. 第二个考虑可能也会解决第一个问题,因为它会将...VALUES (3, )...更改为...VALUES (3, '')...,这会提供空字符串插入。

    我认为,MPO_REFERENCE无法包围单引号,因为它是一个数字。