【问题标题】:How do i consolidate multiple SQL update statements in a macro?如何在一个宏中合并多个 SQL 更新语句?
【发布时间】:2014-06-23 18:40:53
【问题描述】:

我有以下通过 VBA 执行的更新语句。拥有多个更新语句似乎不是最佳选择。我如何将这些合并到一个语句中?这些语句更新 Access 数据库。

strSqlLoc = "UPDATE table1 AS type SET type.Value='" & Range("C" & i).Value & "' WHERE PropertyID=" & Range("B" & i).Value & ";"
strSqlEnv = "UPDATE table1 AS type SET type.Value='" & Range("E" & i).Value & "' WHERE PropertyID=" & Range("D" & i).Value & ";"
strSqlClass = "UPDATE table1 AS type SET type.Value='" & Range("G" & i).Value & "' WHERE PropertyID=" & Range("F" & i).Value & ";"

Set rs = cn.Execute(strSqlLoc)
Set rs = cn.Execute(strSqlEnv)
Set rs = cn.Execute(strSqlClass)

【问题讨论】:

  • 我不知道它是否会起作用,但你也许可以编写一个长的批处理语句并一次执行整个批处理。

标签: sql vba ms-access


【解决方案1】:

另一个更新

对于多行更新,Batch Update 似乎可以解决问题。

Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset

Dim strSQL As String
Dim lngUpdated As Long

rst.ActiveConnection = CurrentProject.Connection
rst.CursorType = adOpenKeyset
rst.CursorLocation = adUseClient
rst.LockType = adLockBatchOptimistic
rst.Open ("Select * from table1 ")

lngUpdated = 1

rst.Find "PropertyID=" & Range("B1")

Do Until rst.EOF
    rst("Value") = Range("C" & lngUpdated)
    lngUpdated = lngUpdated + 1
    rst.Find "PropertyID=" & Range("B" & lngUpdated), 1, adSearchForward
Loop

// Try repeating above for the other two columns?

rst.UpdateBatch

rst.Close
Set rst = Nothing

真的没有比这更好的了,除非您要更新的数据已经在数据库中的某个位置。您可以尝试here 中描述的 case 语句技术

更新:

我认为批量上传想法背后的直觉是,如果您能够以某种方式一次性获取服务器端的数据,那么您可以加入它并在一个更新语句中更新另一个表。如果您只更新三个值 - 考虑在访问端创建一个查询并在一次调用中传递您的六个参数,然后在查询中使用here 描述的技术

【讨论】:

  • 嗯,这意味着我会在更新之前根据数据库验证每条记录。这不会增加额外的负担吗?真的有必要吗?
  • @PeanutsMonkey 我相信你是对的。
  • 你们是对的,我在上面做了一些澄清更新
  • @Alex M - 目的是使用 Excel 作为前端将其一次性上传到数据库。将有超过 3 个查询。可能高达 30,因此需要对其进行优化。
  • 使用未经测试的 BatchUpdate 尝试进行了一些更新,可能与事实相去甚远,但应该给出想法
猜你喜欢
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多