2

我需要执行多个 SQL 语句(INSERT、UPDATE 等...),但如果它在任何时候失败,请将它们全部回滚。

我通常使用 docmd.runsql "INSERT INTO..."

我怎样才能实现交易。

4

1 回答 1

2

如何:在 DAO 记录集中使用事务。根据您的查询,可能无法在 MS Access 的一个事务中运行所有查询。

Sub ChangeTitle()

Dim wrkCurrent As DAO.Workspace
Dim dbsNorthwind As DAO.Database
Dim rstEmployee As DAO.Recordset

On Error GoTo ErrorHandler

   Set wrkCurrent = DBEngine.Workspaces(0)
   Set dbsNorthwind = CurrentDB
   Set rstEmployee = dbsNorthwind.OpenRecordset("Employees")

   wrkCurrent.BeginTrans
   Do Until rstEmployee.EOF
      If rstEmployee!Title = "Sales Representative" Then
         rstEmployee.Edit
         rstEmloyee!Title = "Sales Associate"
         rstEmployee.Update
      End If
      rstEmployee.MoveNext
   Loop

   If MsgBox("Save all changes?", vbQuestion + vbYesNo) = vbYes Then
      wrkCurrent.CommitTrans
   Else
      wrkCurrent.Rollback
   End If

   rstEmployee.Close
   dbsNorthwind.Close
   wrkCurrent.Close

   Set rstEmployee = nothing
   Set dbsNorthwind = Nothing
   Set wrkCurrent = Nothing

   Exit Sub

ErrorHandler:
   MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description
End Sub

Stackoverflow 上的其他帖子

更多信息: http: //msdn.microsoft.com/en-us/library/office/bb208950 (v=office.12).aspx

With queries

Sub RunQueries()
On Error GoTo errtrap

'Set up all the declarations and begin the transactions
Dim wks As DAO.Workspace
Dim db As DAO.Database
Dim sSQL As String

Set wks = DBEngine.Workspaces(0)
Set db = CurrentDb

wks.BeginTrans

sSQL = "UPDATE Table1 SET AText = 'P'"
db.Execute sSQL, dbFailOnError

db.Execute "Query1", dbFailOnError

'This will fail
sSQL = "UPDATE Table1 SET ANumber = 'P'"
db.Execute sSQL, dbFailOnError

wks.CommitTrans

exithere:

db.Close
wks.Close
Exit Sub

errtrap:

' Something happened so all the queries are not committed
wks.Rollback
GoTo exithere

End Sub
于 2012-08-29T13:06:26.477 回答