2

複数の SQL ステートメント (INSERT、UPDATE など) を実行する必要がありますが、いずれかの時点で失敗した場合は、それらをすべてロールバックします。

私は通常 docmd.runsql "INSERT INTO..." を使用します

トランザクションを実装するにはどうすればよいですか。

4

1 に答える 1

2

How to: Use Transactions in a DAO Recordsetから。クエリによっては、MS Access の 1 つのトランザクション内ですべてを実行できない場合があります。

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 に答える