SQL事务回滚失败

时间:2011-11-11 03:26:20

标签: sql vb.net

我有2个表要插入数据,表“CAM”和表“COut”,在“CAM”中插入数据后,它将返回一个retAutoID,它将作为参数之一的“COut”插入所需。我在我的业务逻辑中实现了回滚,这样如果“Cout”在插入时遇到异常错误,“CAM”的先前插入即使成功也会回滚。

使用下面的代码,我在尝试执行插入后收到此错误: “当分配给命令的连接处于挂起的本地事务中时,ExecuteNonQuery要求命令具有事务。该命令的Transaction属性尚未初始化。”

我认为问题可能是由于:

dbCommand = GetStoredProcedureCommand(“COut_Add”) dbCommand.Connection = dbConnection

如果我完全删除“Cout”的第二个数据插入,我就不会有问题。请善意的建议。感谢。

Public Function InsertCM(ByVal objCMBLL As CMBLL, ByVal dbTrans As DbTransaction, ByVal dbConnection As DbConnection, ByVal COut As DataSet) As Boolean

  Dim dbCommand As DbCommand = Nothing
  Dim retAutoID As Int32 = Nothing
  Dim bol_Success As Boolean = False

  Try
    If dbConnection.State <> ConnectionState.Open Then
      dbConnection.Open()
    End If

    dbCommand = GetStoredProcedureCommand("CAM_Add")
    dbCommand.Connection = dbConnection
    dbCommand.Transaction = dbTrans

    With objCMBLL 
      AddInParameter(dbCommand, "@Code", DbType.String, 50, DBNull.Value)
      If Not String.IsNullOrEmpty(.CamCode) Then
        dbCommand.Parameters("@Code").Value = .CamCode
      End If
      retAutoID = CType(ExecuteScalar(dbCommand), Integer)

      dbCommand = GetStoredProcedureCommand("COut_Add")
      dbCommand.Connection = dbConnection

      For i As Integer = 0 To COut.Tables("COut").Rows.Count - 1
        dbCommand.Parameters.Clear()

        AddInParameter(dbCommand, "@Ol_Code", DbType.String, 50, DBNull.Value)$
        dbCommand.Parameters("@Ol_Code").Value = COut.Tables("CampaignOutlets").Rows(i).Item(0).ToString

        AddInParameter(dbCommand, "@Campaign_AutoID", DbType.Int32, 0, DBNull.Value)
        dbCommand.Parameters("@Campaign_AutoID").Value = retAutoID

      Next i
      ExecuteNonQuery(dbCommand)
    End With  

    bol_Success = True

  Catch ex As Exception
    Throw New DALException(ex, dbCommand, Caching.GetCustomerCodeCookie(), "InsertCampaignManagementTable")
  Finally
    If Not dbCommand Is Nothing Then
      dbCommand.Dispose()
    End If
  End Try
  Return bol_Success
End Function

2 个答案:

答案 0 :(得分:1)

好的结果是我没有为'tbl“COut”包含'dbCommand.Transaction = dbTrans'。

答案 1 :(得分:0)

我在你的代码中看到了:

dbCommand.Connection = dbConnection(第二次)。

你真的需要为命令重新分配连接吗?我想你不应该。我们应该只重新分配Command对象的sql文本。 它应该是这样的:

dbCommand.text = GetStoredProcedureCommand(“COUt”)

而不是

dbCommand = GetStoredProcedureCommand(“COut_Add”) dbCommand.Connection = dbConnection

并且

for i As Integer = 0 To COut.Tables(“COut”)。Rows.Count - 1         dbCommand.Parameters.Clear()

我想你必须在循环之前调用dbCommand.Parameters.Clear()。

HTH。