Aracılığıyla paylaş


Geçerli hareket erişme

Çalışan, hangi ortak dil çalışma zamanı (clr) kod noktada en etkin bir hareket olduğu, SQL Server ise girilen hareket yoluyla maruz System.Transactions.Transaction WalkTreeThe Transaction.Current property is used to access the current transaction.Çoğu zaman hareket açıkça erişmek gerekli değildir.Veritabanı bağlantıları için ado.net çek Transaction.Current otomatik olarak Connection.Open yöntem çağrılır ve şeffaf bağlantı o işleme kaydeder (sürece Enlist anahtar bağlantı false olarak küme dize).

Kullanmak istediğiniz Transaction nesnesi doğrudan aşağıdaki senaryolarda:

  • Bir kaynak listeleme istiyorsanız, otomatik kayıt yapın veya herhangi bir nedenle, başlatma sırasında kayıtlı.

  • Açıkça bir kaynak olarak hareket listeleme istiyorsanız.

  • Saklı yordam veya işlev içinde dış hareketinden sonlandırmak isterseniz.Bu durum, kullandığınız TransactionScope.Örneğin, aşağıdaki kod olacak rollback geçerli hareket:

    using(TransactionScope transactionScope = new TransactionScope(TransactionScopeOptions.Required)) { }
    

Bu konu geri kalanını bir dış işlemi iptal etmek için başka yolları açıklanır.

Bir dış işlemi iptal ediliyor

Aşağıdaki şekillerde yönetilen yordam veya işlev dış işlemler iptal edebilirsiniz:

  • Yönetilen yordam veya işlev bir çıktı parametresini kullanarak bir değer döndürebilirsiniz.Arama Transact-SQL yordam döndürülen değer kontrol edin ve uygun ise, yürütmek ROLLBACK TRANSACTION.

  • Yönetilen yordam veya işlev bir özel istisna.Arama Transact-SQL yordam tarafından yönetilen yordam veya işlev bir try/catch bloğu içinde atılan özel durum yakalamak ve yürütmek ROLLBACK TRANSACTION.

  • Yönetilen yordam veya işlev geçerli hareket çağırarak iptal edebilirsiniz Transaction.Rollback yöntem, belirli bir koşul olduğu met.

Bir yönetilen yordam veya işlev içinde çağrıldığında Transaction.Rollback yöntem ile belirsiz bir hata iletisi bir istisna atar ve bir try/catch sarılan blok.Hata iletisi thresembles aşağıdakine benzer:

Msg 3994, Level 16, State 1, Procedure uspRollbackFromProc, Line 0
Transaction is not allowed to roll back inside a user defined routine, trigger or aggregate because the transaction is not started in that CLR level. Change application logic to enforce strict transaction nesting.

Bu özel durumu beklenir ve try veya catch blok kod yürütülmesine devam etmek için gereklidir.Try veya catch olmadan blok, özel arama için hemen durum Transact-SQL yordam ve yönetilen kod yürütülmesine olacak son.Yönetilen kod yürütme tamamlandığında, başka bir özel durum ortaya çıkar:

Msg 3991, Level 16, State 1, Procedure uspRollbackFromProc, Line 1 
The context transaction which was active before entering user defined routine, trigger or aggregate " uspRollbackFromProc " has been ended inside of it, which is not allowed. Change application logic to enforce strict transaction nesting. The statement has been terminated.

Bu durum da beklenen ve yürütülmesine devam etmek bir try/catch olmalıdır blok etrafında Transact-SQL deyim, harekete eylem gerçekleştirirtetikleyici. Rağmen atılan iki özel durumları, işlem geri alınır ve değişiklikleri edilendir.

Örnek

Yönetilen bir yordam kullanarak geri alınmakta olan bir hareketin bir örnek şudur Transaction.Rollback yöntem.Try/catch bloðu çevresine dikkat edin Transaction.Rollback yöntem yönetilen kod.The Transact-SQL script creates an assembly and managed stored procedure.Dikkat edin, EXEC uspRollbackFromProc bir try/catch deyim sarılan blok, böylece yönetilen yordam yürütme tamamlandığında durum özel durum yakalandı.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Transactions;

public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void uspRollbackFromProc()
{
   using (SqlConnection connection = new SqlConnection(@"context connection=true"))
   {
      // Open the connection.
      connection.Open();

      bool successCondition = true;

      // Success condition is met.
      if (successCondition)
      {
         SqlContext.Pipe.Send("Success condition met in procedure."); 
         // Perform other actions here.
      }
            
      //  Success condition is not met, the transaction will be rolled back.
      else
      {
         SqlContext.Pipe.Send("Success condition not met in managed procedure. Transaction rolling back...");
         try
         {
               // Get the current transaction and roll it back.
               Transaction trans = Transaction.Current;
               trans.Rollback();
         }
         catch (SqlException ex)
         {
            // Catch the expected exception. 
            // This allows the connection to close correctly.                    
         }  
      }

      // Close the connection.
      connection.Close();
   }
}
};
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.Transactions

Partial Public Class StoredProcedures
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub  uspRollbackFromProc ()
   Using connection As New SqlConnection("context connection=true")

   ' Open the connection.
   connection.Open()

   Dim successCondition As Boolean
   successCondition = False

   ' Success condition is met.
   If successCondition Then

      SqlContext.Pipe.Send("Success condition met in procedure.")

      ' Success condition is not met, the transaction will be rolled back.

   Else
      SqlContext.Pipe.Send("Success condition not met in managed procedure. Transaction rolling back...")
      Try
         ' Get the current transaction and roll it back.
         Dim trans As Transaction
         trans = Transaction.Current
         trans.Rollback()

      Catch ex As SqlException
         ' Catch the exception instead of throwing it.  
         ' This allows the connection to close correctly.                    
      End Try

   End If

   ' Close the connection.
   connection.Close()

End Using
End Sub
End Class

Transact-SQL

--Register assembly.
CREATE ASSEMBLY TestProcs FROM 'C:\Programming\TestProcs.dll' 
Go
CREATE PROCEDURE uspRollbackFromProc AS EXTERNAL NAME TestProcs.StoredProcedures.uspRollbackFromProc
Go

-- Execute procedure.
BEGIN TRY
BEGIN TRANSACTION 
-- Perform other actions.
Exec uspRollbackFromProc
-- Perform other actions.
PRINT N'Commiting transaction...'
COMMIT TRANSACTION
END TRY

BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNum, ERROR_MESSAGE() AS ErrorMessage
PRINT N'Exception thrown, rolling back transaction.'
ROLLBACK TRANSACTION
PRINT N'Transaction rolled back.' 
END CATCH
Go

-- Clean up.
DROP Procedure uspRollbackFromProc;
Go
DROP ASSEMBLY TestProcs;
Go

Ayrıca bkz.

Kavramlar