2013-07-28 78 views
0

是否有可能做这样的事情:的TransactionScope混乱

Imports System.Data.SqlClient 
Imports System.Configuration 
Imports System.Transactions 

Public Class Form1 
    Private _ConString As String 
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 
     Dim objDR As SqlDataReader 
     Dim objCommand As SqlCommand, objCommand2 As SqlCommand 
     Dim objCon As SqlConnection 
     Dim objCon2 As SqlConnection 
     Dim id As Integer 
     Try 
      _ConString = "Data Source=IANSCOMPUTER;Initial Catalog=AdventureWorks2008R2;Integrated Security=True;MultipleActiveResultSets=true" 
       objCon = New SqlConnection(_ConString) 
       objCommand = New SqlCommand("SELECT * FROM PERSON.PERSON WHERE BusinessEntityID<=10") 
       objCommand2 = New SqlCommand() 
       objCommand.Connection = objCon 
       objCommand2.Connection = objCon 
       objCon.Open() 
       objDR = objCommand.ExecuteReader(ConnectionState.Closed) 
      Do While objDR.Read 
       Using scope As New TransactionScope 
        objCon2 = New SqlConnection(_ConString) 
        objCon2.Open() 
        Using objCon2 
         objCommand2.CommandText = "UPDATE Person.Person SET middlename = @middlename WHERE " & _ 
          " Person.BusinessEntityID = @ID " 
         objCommand2.Parameters.AddWithValue("@middlename", objDR("BusinessEntityID") + 1) 
         objCommand2.Parameters.AddWithValue("@ID", objDR("BusinessEntityID")) 
         objCommand2.ExecuteNonQuery() 
         objCommand2.Parameters.Clear() 
        End Using 
       End Using 
      Loop 
      objDR.Close() 'line 16 
     Catch ex As Exception 
      Throw 
     Finally 

     End Try 

    End Sub 
End Class 

在上面的代码,为每个循环创建事务。我想这样做的原因是因为表被锁定,直到while循环结束。上述代码的问题是忽略了事务的创建。

+1

你不提交事务,使用(''scope.Complete()'](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.complete.aspx)(就在TransactionScope的'End Using'之前) 。 – Styxxy

回答

0

1您不需要使用2个不同的SqlCommands变量。 第二尝试使用范围while循环之前,改变“objDR = objCommand.ExecuteReader(ConnectionState.Closed)”这个“objDR = objCommand.ExecuteReader()” 3试

+0

如果我把范围放在开头(在while循环之外),那么它就起作用了。关键是我想在while循环中挖掘范围。 – w0051977