简体   繁体   中英

C# : SQL Transaction

Is it possible to retrieve the current SQL Transaction in c# when connection was closed?

sqlTransaction.Save("savePoint"); 
sqlConnection.Close()              // im purposely closing it to test 

if (sqlConnection.State == ConnectionState.Close)
{
    sqlConnection.Open():

   // is it possible to resume the sql transaction when I re-open    
   // the sql connection? how? 
}

连接终止时,没有SQL Server将回滚任何未提交的事务。

SqlTransaction.Save does not 'save' the transaction, instead it creates a transaction savepoint, which is something completely different:

Creates a savepoint in the transaction that can be used to roll back a part of the transaction, and specifies the savepoint name.

A savepoint can be used before the transaction is committed to partially rollback some of the work done by the transaction. A typical example would be an attempt to do an update that may fail, so you create a savepoint before doing the update and in case of failure you rollback to the savepoint, thus preserving all the work done prior to the savepoint.

See Exception handling and nested transactions for an example of how to use savepoints.

Now back to your question, is there a way for a connection to start a connection, close, and when re-open, pick up the same transaction? Technically there is, by using the (now deprecated) sp_getbindtoken and sp_bindsession . But this is just a curiosity, there is absolutely no valid scenario for you to attempt to 'reuse' a transaction across two different sessions (two re-opens of a connection).

This seems to be a misunderstanding of a database transaction. Transactions are all-or-nothing conversations with the database. If you close the line of communication with the database by closing the connection, the conversation is over and the changes are not committed (the "nothing" part of "all-or-nothing").

不,我认为您不能这样做。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM