SqlTransaction.Rollback SqlTransaction.Rollback SqlTransaction.Rollback SqlTransaction.Rollback Method

Definición

Revierte una transacción desde un estado pendiente. Rolls back a transaction from a pending state.

Sobrecargas

Rollback() Rollback() Rollback() Rollback()

Revierte una transacción desde un estado pendiente. Rolls back a transaction from a pending state.

Rollback(String) Rollback(String) Rollback(String) Rollback(String)

Deshace una transacción con un estado pendiente y especifica el nombre de la transacción o del punto de almacenamiento. Rolls back a transaction from a pending state, and specifies the transaction or savepoint name.

Rollback() Rollback() Rollback() Rollback()

Revierte una transacción desde un estado pendiente. Rolls back a transaction from a pending state.

public:
 override void Rollback();
public override void Rollback ();
override this.Rollback : unit -> unit
Public Overrides Sub Rollback ()
Implementaciones
Excepciones

Error al intentar confirmar la transacción. An error occurred while trying to commit the transaction.

Ya se confirmó o revirtió la transacción. The transaction has already been committed or rolled back. O bien -or- Se interrumpió la conexión. The connection is broken.

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 el BeginTransaction, Commit, y Rollback métodos.It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. La transacción se revierte en ningún error.The transaction is rolled back on any error. Try/Catch control de errores se usa para controlar los errores cuando se intenta confirmar o revertir la transacción.Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.

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

El Rollback método es equivalente a la instrucción ROLLBACK TRANSACTION de Transact-SQL.The Rollback method is equivalent to the Transact-SQL ROLLBACK TRANSACTION statement. Para obtener más información, consulte ROLLBACK TRANSACTION (Transact-SQL) .For more information, see ROLLBACK TRANSACTION (Transact-SQL) .

La transacción sólo se puede deshacer desde un estado pendiente (después de BeginTransaction se ha llamado, pero antes Commit se denomina).The transaction can only be rolled back from a pending state (after BeginTransaction has been called, but before Commit is called). La transacción se revierte en el evento se elimina antes Commit o Rollback se llama.The transaction is rolled back in the event it is disposed before Commit or Rollback is called.

Nota

Try/Catch siempre se debe usar el control de excepciones cuando se revierte una transacción.Try/Catch exception handling should always be used when rolling back a transaction. Un Rollback genera un InvalidOperationException cuando se termina la conexión o si la transacción ya se ha deshecho en el servidor.A Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the 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).

Consultar también

Rollback(String) Rollback(String) Rollback(String) Rollback(String)

Deshace una transacción con un estado pendiente y especifica el nombre de la transacción o del punto de almacenamiento. Rolls back a transaction from a pending state, and specifies the transaction or savepoint name.

public:
 void Rollback(System::String ^ transactionName);
public void Rollback (string transactionName);
override this.Rollback : string -> unit
Public Sub Rollback (transactionName As String)
Parámetros
transactionName
String String String String

Nombre de la transacción que se va a deshacer o punto de guardado en el que se va a deshacer. The name of the transaction to roll back, or the savepoint to which to roll back.

Excepciones

No se ha especificado ningún nombre de transacción. No transaction name was specified.

Ya se confirmó o revirtió la transacción. The transaction has already been committed or rolled back. O bien -or- Se interrumpió la conexión. The connection is broken.

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 el BeginTransaction, Commit, y Rollback métodos.It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. La transacción se revierte en ningún error.The transaction is rolled back on any error. Try/Catch control de errores se usa para controlar los errores cuando se intenta confirmar o revertir la transacción.Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.

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

El Rollback método es equivalente a la instrucción ROLLBACK TRANSACTION de Transact-SQL.The Rollback method is equivalent to the Transact-SQL ROLLBACK TRANSACTION statement. Para obtener más información, consulte transacciones (Transact-SQL).For more information, see Transactions (Transact-SQL).

La transacción sólo se puede deshacer desde un estado pendiente (después de BeginTransaction se ha llamado, pero antes Commit se denomina).The transaction can only be rolled back from a pending state (after BeginTransaction has been called, but before Commit is called). La transacción se revierte si se elimina antes Commit o Rollback se llama.The transaction is rolled back if it is disposed before Commit or Rollback is called.

Nota

Try/Catch siempre se debe usar el control de excepciones cuando se revierte una transacción.Try/Catch exception handling should always be used when rolling back a transaction. Un Rollback genera un InvalidOperationException cuando se termina la conexión o si la transacción ya se ha deshecho en el servidor.A Rollback generates an InvalidOperationException if the connection is terminated or if the transaction has already been rolled back on the 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).

Consultar también

Se aplica a