0

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

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 循环完成。上面代码的问题是忽略了事务的创建。

4

1 回答 1

0

首先,您不需要使用 2 个不同的 SqlCommands 变量。第二次尝试将“objDR = objCommand.ExecuteReader(ConnectionState.Closed)”更改为此“objDR = objCommand.ExecuteReader()”第三次尝试使用 while 循环之前的范围

于 2013-07-28T19:28:02.350 回答