提交事务请求没有使用ADO.net的相应开始事务

时间:2018-04-26 16:34:26

标签: ado.net sqltransaction

我想在SqlTransaction中批量更新记录。在每批中我都在更新50条记录。如果任何一条记录无法更新,我想要回滚这50条记录。我在while循环中编写了这段代码。但我随机得到以下错误。 '提交事务请求没有相应的开始事务'。

以下是我的代码:

Dim _completed as Integer=0
Dim sqlCon As SqlClient.SqlConnection = Nothing
Dim sqlTransaction As SqlClient.SqlTransaction = Nothing
Dim lstq as List(of SqlCommand) 'It contains list of update queries 
sqlCon = New SqlClient.SqlConnection(AIMSCommon.sqlServerConnection)
sqlCon.Open()
While True
    Dim _res = lstq.Skip(_completed).Take(40)
    If _res.Count = 0 Then Exit While
    If sqlCon.State <> ConnectionState.Open Then
      sqlCon = New SqlClient.SqlConnection(AIMSCommon.sqlServerConnection)
      sqlCon.Open()
    End If
    Try
      sqlTransaction = sqlCon.BeginTransaction()
                    For Each cls In _res
                        Try
                            cls.Connection = sqlCon
                            cls.Transaction = sqlTransaction
                            Dim i As Integer = cls.ExecuteNonQuery()
                            cls.Dispose()
                        Catch ex As Exception
                            If cls IsNot Nothing Then
                                cls.Dispose()
                            End If
                            Throw ex
                        End Try
                    Next
                sqlTransaction.Commit()
                sqlTransaction.Dispose()
                sqlTransaction = Nothing
                _completed += _res.Count
                Catch ex As Exception
                    sqlCon.Close()
                    sqlCon.Dispose()
                    If sqlTransaction IsNot Nothing Then
                        sqlTransaction.Rollback()
                        sqlTransaction.Dispose()
                    End If
                    If sqlCon IsNot Nothing Then
                        sqlCon.Close()
                        sqlCon.Dispose()
                    End If

                End Try
            End While
            If sqlCon IsNot Nothing Then
                sqlCon.Close()
                sqlCon.Dispose()
            End If

0 个答案:

没有答案