SqlConnection.BeginTransaction Método

Definición

Inicia una transacción de base de datos.Starts a database transaction.

Sobrecargas

BeginTransaction()

Inicia una transacción de base de datos.Starts a database transaction.

BeginTransaction(IsolationLevel)

Inicia una transacción de base de datos con el nivel de aislamiento especificado.Starts a database transaction with the specified isolation level.

BeginTransaction(String)

Inicia una transacción de base de datos con el nombre de transacción especificado.Starts a database transaction with the specified transaction name.

BeginTransaction(IsolationLevel, String)

Inicia una transacción de la base de datos con el nivel de aislamiento y el nombre de transacción especificados.Starts a database transaction with the specified isolation level and transaction name.

BeginTransaction()

Inicia una transacción de base de datos.Starts a database transaction.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction();
public System.Data.SqlClient.SqlTransaction BeginTransaction ();
override this.BeginTransaction : unit -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : unit -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction () As SqlTransaction

Devoluciones

Un objeto que representa la nueva transacción.An object representing the new transaction.

Excepciones

No se permiten transacciones paralelas al usar Conjuntos de resultados activos múltiples (MARS).Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).

No se admiten transacciones paralelas.Parallel transactions are not supported.

Ejemplos

En el ejemplo siguiente se crea un SqlConnection y un SqlTransaction.The following example creates a SqlConnection and a SqlTransaction. También se muestra cómo usar los métodos BeginTransaction, Commity Rollback.It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction
        transaction = connection.BeginTransaction("SampleTransaction")

        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction.
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"

            command.ExecuteNonQuery()

            ' Attempt to commit the transaction.
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")

        Catch ex As Exception
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType())
            Console.WriteLine("  Message: {0}", ex.Message)

            ' Attempt to roll back the transaction.
            Try
                transaction.Rollback()

            Catch ex2 As Exception
                ' This catch block will handle any errors that may have occurred
                ' on the server that would cause the rollback to fail, such as
                ' a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
                Console.WriteLine("  Message: {0}", ex2.Message)
            End Try
        End Try
    End Using
End Sub

Comentarios

Este comando se asigna a la implementación de SQL Server de BEGIN TRANSACTION.This command maps to the SQL Server implementation of BEGIN TRANSACTION.

Debe confirmar o revertir explícitamente la transacción mediante el método Commit o Rollback.You must explicitly commit or roll back the transaction using the Commit or Rollback method. Para asegurarse de que el modelo de administración de transacciones de .NET Framework para SQL Server funcione correctamente, evite el uso de otros modelos de administración de transacciones, como el proporcionado por SQL Server.To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.

Nota

Si no especifica un nivel de aislamiento, se utiliza el nivel de aislamiento predeterminado.If you do not specify an isolation level, the default isolation level is used. Para especificar un nivel de aislamiento con el método BeginTransaction, use la sobrecarga que toma el parámetro iso (BeginTransaction).To specify an isolation level with the BeginTransaction method, use the overload that takes the iso parameter (BeginTransaction). El nivel de aislamiento establecido para una transacción persiste después de completarse la transacción y hasta que la conexión se cierra o se desecha.The isolation level set for a transaction persists after the transaction is completed and until the connection is closed or disposed. Al establecer el nivel de aislamiento en Snapshot en una base de datos en la que el nivel de aislamiento de instantánea no está habilitado, no se produce una excepción.Setting the isolation level to Snapshot in a database where the snapshot isolation level is not enabled does not throw an exception. La transacción se completará con el nivel de aislamiento predeterminado.The transaction will complete using the default isolation level.

Precaución

Si se inicia una transacción y se produce un error de nivel 16 o superior en el servidor, la transacción no se revertirá hasta que se invoque el método de Read.If a transaction is started and a level 16 or higher error occurs on the server, the transaction will not be rolled back until the Read method is invoked. No se produce ninguna excepción en ExecuteReader.No exception is thrown on ExecuteReader.

Precaución

Cuando la consulta devuelve una gran cantidad de datos y llama a BeginTransaction, se produce una SqlException porque SQL Server no permite transacciones paralelas cuando se usa MARS.When your query returns a large amount of data and calls BeginTransaction, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. Para evitar este problema, asocie siempre una transacción con el comando, la conexión o ambas antes de que se abran los lectores.To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.

Para obtener más información sobre las transacciones de SQL Server, vea transacciones (Transact-SQL).For more information on SQL Server transactions, see Transactions (Transact-SQL).

Consulte también:

BeginTransaction(IsolationLevel)

Inicia una transacción de base de datos con el nivel de aislamiento especificado.Starts a database transaction with the specified isolation level.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso);
public System.Data.SqlClient.SqlTransaction BeginTransaction (System.Data.IsolationLevel iso);
override this.BeginTransaction : System.Data.IsolationLevel -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : System.Data.IsolationLevel -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel) As SqlTransaction

Parámetros

iso
IsolationLevel

Nivel de aislamiento en el que tiene que ejecutarse la transacción.The isolation level under which the transaction should run.

Devoluciones

Un objeto que representa la nueva transacción.An object representing the new transaction.

Excepciones

No se permiten transacciones paralelas al usar Conjuntos de resultados activos múltiples (MARS).Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).

No se admiten transacciones paralelas.Parallel transactions are not supported.

Ejemplos

En el ejemplo siguiente se crea un SqlConnection y un SqlTransaction.The following example creates a SqlConnection and a SqlTransaction. También se muestra cómo usar los métodos BeginTransaction, Commity Rollback.It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted);

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception e)
        {
            try
            {
                transaction.Rollback();
            }
            catch (SqlException ex)
            {
                if (transaction.Connection != null)
                {
                    Console.WriteLine("An exception of type " + ex.GetType() +
                        " was encountered while attempting to roll back the transaction.");
                }
            }

            Console.WriteLine("An exception of type " + e.GetType() +
                " was encountered while inserting the data.");
            Console.WriteLine("Neither record was written to database.");
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction
        transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted)
        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
            command.ExecuteNonQuery()
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")
        Catch e As Exception
            Try
                transaction.Rollback()
            Catch ex As SqlException
                If Not transaction.Connection Is Nothing Then
                    Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
                      " was encountered while attempting to roll back the transaction.")
                End If
            End Try

            Console.WriteLine("An exception of type " & e.GetType().ToString() & _
              "was encountered while inserting the data.")
            Console.WriteLine("Neither record was written to database.")
        End Try
    End Using
End Sub

Comentarios

Este comando se asigna a la implementación de SQL Server de BEGIN TRANSACTION.This command maps to the SQL Server implementation of BEGIN TRANSACTION.

Debe confirmar o revertir explícitamente la transacción mediante el método Commit o Rollback.You must explicitly commit or roll back the transaction using the Commit or Rollback method. Para asegurarse de que el modelo de administración de transacciones de .NET Framework para SQL Server funcione correctamente, evite el uso de otros modelos de administración de transacciones, como el proporcionado por SQL Server.To make sure that the .NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.

Nota

Después de confirmar o revertir una transacción, el nivel de aislamiento de la transacción se conserva para todos los comandos subsiguientes que están en modo de confirmación automática (el valor predeterminado SQL Server).After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). Esto puede producir resultados inesperados, como un nivel de aislamiento de lectura REPETIble que conserva y bloqueo de otros usuarios fuera de una fila.This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. Para restablecer el nivel de aislamiento al predeterminado (lectura confirmada), ejecute la instrucción Transact-SQLTransact-SQL establecer el nivel de aislamiento de transacción READ COMMITTED o llame a SqlConnection.BeginTransaction seguido inmediatamente de SqlTransaction.Commit.To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQLTransact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call SqlConnection.BeginTransaction followed immediately by SqlTransaction.Commit. Para obtener más información sobre los niveles de aislamiento de SQL Server, vea niveles de aislamiento de transacción.For more information on SQL Server isolation levels, see Transaction Isolation Levels.

Para obtener más información sobre las transacciones de SQL Server, vea transacciones (Transact-SQL).For more information on SQL Server transactions, see Transactions (Transact-SQL).

Precaución

Cuando la consulta devuelve una gran cantidad de datos y llama a BeginTransaction, se produce una SqlException porque SQL Server no permite transacciones paralelas cuando se usa MARS.When your query returns a large amount of data and calls BeginTransaction, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. Para evitar este problema, asocie siempre una transacción con el comando, la conexión o ambas antes de que se abran los lectores.To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.

Consulte también:

BeginTransaction(String)

Inicia una transacción de base de datos con el nombre de transacción especificado.Starts a database transaction with the specified transaction name.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::String ^ transactionName);
public System.Data.SqlClient.SqlTransaction BeginTransaction (string transactionName);
override this.BeginTransaction : string -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : string -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (transactionName As String) As SqlTransaction

Parámetros

transactionName
String

El nombre de la transacción.The name of the transaction.

Devoluciones

Un objeto que representa la nueva transacción.An object representing the new transaction.

Excepciones

No se permiten transacciones paralelas al usar Conjuntos de resultados activos múltiples (MARS).Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).

No se admiten transacciones paralelas.Parallel transactions are not supported.

Ejemplos

En el ejemplo siguiente se crea un SqlConnection y un SqlTransaction.The following example creates a SqlConnection and a SqlTransaction. También se muestra cómo usar los métodos BeginTransaction, Commity Rollback.It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction.
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred
                // on the server that would cause the rollback to fail, such as
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction
        transaction = connection.BeginTransaction("SampleTransaction")

        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction.
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"

            command.ExecuteNonQuery()

            ' Attempt to commit the transaction.
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")

        Catch ex As Exception
            Console.WriteLine("Exception Type: {0}", ex.GetType())
            Console.WriteLine("  Message: {0}", ex.Message)

            ' Attempt to roll back the transaction.
            Try
                transaction.Rollback()

            Catch ex2 As Exception
                ' This catch block will handle any errors that may have occurred
                ' on the server that would cause the rollback to fail, such as
                ' a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType())
                Console.WriteLine("  Message: {0}", ex2.Message)
            End Try
        End Try
    End Using
End Sub

Comentarios

Este comando se asigna a la implementación de SQL Server de BEGIN TRANSACTION.This command maps to the SQL Server implementation of BEGIN TRANSACTION.

La longitud del parámetro transactionName no debe superar los 32 caracteres; de lo contrario, se producirá una excepción.The length of the transactionName parameter must not exceed 32 characters; otherwise an exception will be thrown.

El valor del parámetro transactionName se puede utilizar en llamadas posteriores a Rollback y en el parámetro savePoint del método Save.The value in the transactionName parameter can be used in later calls to Rollback and in the savePoint parameter of the Save method.

Debe confirmar o revertir explícitamente la transacción mediante el método Commit o Rollback.You must explicitly commit or roll back the transaction using the Commit or Rollback method. Para asegurarse de que el modelo de administración de transacciones de .NET Framework.NET Framework para SQL Server funcione correctamente, evite el uso de otros modelos de administración de transacciones, como el proporcionado por SQL Server.To make sure that the .NET Framework.NET Framework Data Provider for SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.

Para obtener más información sobre las transacciones de SQL Server, vea transacciones (Transact-SQL).For more information on SQL Server transactions, see Transactions (Transact-SQL).

Precaución

Cuando la consulta devuelve una gran cantidad de datos y llama a BeginTransaction, se produce una SqlException porque SQL Server no permite transacciones paralelas cuando se usa MARS.When your query returns a large amount of data and calls BeginTransaction, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. Para evitar este problema, asocie siempre una transacción con el comando, la conexión o ambas antes de que se abran los lectores.To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.

Consulte también:

BeginTransaction(IsolationLevel, String)

Inicia una transacción de la base de datos con el nivel de aislamiento y el nombre de transacción especificados.Starts a database transaction with the specified isolation level and transaction name.

public:
 System::Data::SqlClient::SqlTransaction ^ BeginTransaction(System::Data::IsolationLevel iso, System::String ^ transactionName);
public System.Data.SqlClient.SqlTransaction BeginTransaction (System.Data.IsolationLevel iso, string transactionName);
override this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
member this.BeginTransaction : System.Data.IsolationLevel * string -> System.Data.SqlClient.SqlTransaction
Public Function BeginTransaction (iso As IsolationLevel, transactionName As String) As SqlTransaction

Parámetros

iso
IsolationLevel

Nivel de aislamiento en el que tiene que ejecutarse la transacción.The isolation level under which the transaction should run.

transactionName
String

El nombre de la transacción.The name of the transaction.

Devoluciones

Un objeto que representa la nueva transacción.An object representing the new transaction.

Excepciones

No se permiten transacciones paralelas al usar Conjuntos de resultados activos múltiples (MARS).Parallel transactions are not allowed when using Multiple Active Result Sets (MARS).

No se admiten transacciones paralelas.Parallel transactions are not supported.

Ejemplos

En el ejemplo siguiente se crea un SqlConnection y un SqlTransaction.The following example creates a SqlConnection and a SqlTransaction. También se muestra cómo usar los métodos BeginTransaction, Commity Rollback.It also demonstrates how to use the BeginTransaction, a Commit, and Rollback methods.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction(
            IsolationLevel.ReadCommitted, "SampleTransaction");

        // Must assign both transaction object and connection
        // to Command object for a pending local transaction.
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception e)
        {
            try
            {
                transaction.Rollback();
            }
            catch (SqlException ex)
            {
                if (transaction.Connection != null)
                {
                    Console.WriteLine("An exception of type " + ex.GetType() +
                        " was encountered while attempting to roll back the transaction.");
                }
            }

            Console.WriteLine("An exception of type " + e.GetType() +
                " was encountered while inserting the data.");
            Console.WriteLine("Neither record was written to database.");
        }
    }
}
Private Sub ExecuteSqlTransaction(ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        connection.Open()

        Dim command As SqlCommand = connection.CreateCommand()
        Dim transaction As SqlTransaction

        ' Start a local transaction.
        transaction = connection.BeginTransaction( _
          IsolationLevel.ReadCommitted, "SampleTransaction")

        ' Must assign both transaction object and connection
        ' to Command object for a pending local transaction.
        command.Connection = connection
        command.Transaction = transaction

        Try
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"
            command.ExecuteNonQuery()
            command.CommandText = _
              "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"
            command.ExecuteNonQuery()
            transaction.Commit()
            Console.WriteLine("Both records are written to database.")
        Catch e As Exception
            Try
                transaction.Rollback()
            Catch ex As SqlException
                If Not transaction.Connection Is Nothing Then
                    Console.WriteLine("An exception of type " & ex.GetType().ToString() & _
                      " was encountered while attempting to roll back the transaction.")
                End If
            End Try

            Console.WriteLine("An exception of type " & e.GetType().ToString() & _
              "was encountered while inserting the data.")
            Console.WriteLine("Neither record was written to database.")
        End Try
    End Using
End Sub

Comentarios

Este comando se asigna a la implementación de SQL Server de BEGIN TRANSACTION.This command maps to the SQL Server implementation of BEGIN TRANSACTION.

El valor del parámetro transactionName se puede utilizar en llamadas posteriores a Rollback y en el parámetro savePoint del método Save.The value in the transactionName parameter can be used in later calls to Rollback and in the savePoint parameter of the Save method.

Debe confirmar o revertir explícitamente la transacción mediante el método Commit o Rollback.You must explicitly commit or roll back the transaction using the Commit or Rollback method. Para asegurarse de que el modelo de administración de transacciones de SQL Server funciona correctamente, evite el uso de otros modelos de administración de transacciones, como el proporcionado por SQL Server.To make sure that the SQL Server transaction management model performs correctly, avoid using other transaction management models, such as the one provided by SQL Server.

Nota

Después de confirmar o revertir una transacción, el nivel de aislamiento de la transacción se conserva para todos los comandos subsiguientes que están en modo de confirmación automática (el valor predeterminado SQL Server).After a transaction is committed or rolled back, the isolation level of the transaction persists for all subsequent commands that are in autocommit mode (the SQL Server default). Esto puede producir resultados inesperados, como un nivel de aislamiento de lectura REPETIble que conserva y bloqueo de otros usuarios fuera de una fila.This can produce unexpected results, such as an isolation level of REPEATABLE READ persisting and locking other users out of a row. Para restablecer el nivel de aislamiento al predeterminado (lectura confirmada), ejecute la instrucción Transact-SQLTransact-SQL establecer el nivel de aislamiento de transacción READ COMMITTED o llame a SqlConnection.BeginTransaction seguido inmediatamente de SqlTransaction.Commit.To reset the isolation level to the default (READ COMMITTED), execute the Transact-SQLTransact-SQL SET TRANSACTION ISOLATION LEVEL READ COMMITTED statement, or call SqlConnection.BeginTransaction followed immediately by SqlTransaction.Commit. Para obtener más información sobre los niveles de aislamiento de SQL Server, vea niveles de aislamiento de transacción.For more information on SQL Server isolation levels, see Transaction Isolation Levels.

Para obtener más información sobre las transacciones de SQL Server, vea transacciones (Transact-SQL).For more information on SQL Server transactions, see Transactions (Transact-SQL).

Precaución

Cuando la consulta devuelve una gran cantidad de datos y llama a BeginTransaction, se produce una SqlException porque SQL Server no permite transacciones paralelas cuando se usa MARS.When your query returns a large amount of data and calls BeginTransaction, a SqlException is thrown because SQL Server does not allow parallel transactions when using MARS. Para evitar este problema, asocie siempre una transacción con el comando, la conexión o ambas antes de que se abran los lectores.To avoid this problem, always associate a transaction with the command, the connection, or both before any readers are open.

Consulte también:

Se aplica a