0

2 つのクエリで DB にレコードを挿入するプログラムがあります。そこでトランザクションを処理しています。しかし、私の取引は機能していません。first statement を実行した後、プログラム レコードを閉じると、最初のテーブルが挿入され、2 番目のテーブルには挿入されません。

しかし、それは最初のテーブルからロールバックする必要があります。ここでの問題は何ですか。

Try
objBLlCommonFunction.BeginTransaction()
For j As Integer = 0 To dgstkReceivd.VisibleRowCount - 1
objBllStcTransaction.InsertStockTransferExcelDetail(InvNo, lblDateI.Text)      
Next

objBllStcTransaction.InsertStockTransferExcelHeader(InvNo, dbId)

ScriptManager.RegisterClientScriptBlock(btnSave, btnSave.GetType(), "message", "alert('" + "Successfully Saved" + "');", True)
objBLlCommonFunction.CommitTransaction()
Catch ex As Exception
        objBLlCommonFunction.RollbackTransaction()
        objerror.AddToErrorLog(ex.StackTrace, ex.Message)
        ScriptManager.RegisterClientScriptBlock(btnSave, btnSave.GetType(), "message", "alert('" + ex.Message + "');", True)
End Try

4

1 に答える 1

0

このようなトランザクション スコープを使用する必要があります。

`
Try ' コマンドを実行するための TransactionScope を作成し、 ' 両方のコマンドが単一の作業単位としてコミットまたはロールバックできることを保証します。Using scope As New TransactionScope() Using connection1 As New SqlConnection(connectString1) ' 接続を開くと、
' 軽量トランザクションとして TransactionScope に自動的に登録されます。connection1.Open()

            ' Create the SqlCommand object and execute the first command. 
            Dim command1 As SqlCommand = New SqlCommand(commandText1, connection1)
            returnValue = command1.ExecuteNonQuery()
            writer.WriteLine("Rows to be affected by command1: {0}", returnValue)

            ' If you get here, this means that command1 succeeded. By nesting 
            ' the using block for connection2 inside that of connection1, you 
            ' conserve server and network resources as connection2 is opened 
            ' only when there is a chance that the transaction can commit.    
            Using connection2 As New SqlConnection(connectString2)
                ' The transaction is escalated to a full distributed 
                ' transaction when connection2 is opened.
                connection2.Open()

                ' Execute the second command in the second database.
                returnValue = 0
                Dim command2 As SqlCommand = New SqlCommand(commandText2, connection2)
                returnValue = command2.ExecuteNonQuery()
                writer.WriteLine("Rows to be affected by command2: {0}", returnValue)
            End Using 
        End Using 

    ' The Complete method commits the transaction. If an exception has been thrown, 
    ' Complete is called and the transaction is rolled back.
    scope.Complete()
    End Using 
Catch ex As TransactionAbortedException
    writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message)
Catch ex As ApplicationException
    writer.WriteLine("ApplicationException Message: {0}", ex.Message)
End Try `
于 2015-03-26T06:29:47.967 に答える