SQLTransaction and T-SQL transactions

rollbacksql-server-2005transactionstsql

I am using .NET 2.0 and SQL Server 2005. For historical reasons, the app code is using SQLTransaction but some of the stored procedures are also using T-SQL begin/commit/rollback tran statements. The idea is that the DBTransaction can span many stored procedures, which each individual sproc controls what's happening in its scope – in effect these are nested transactions.

The old behavior of the code was that if any of the sprocs failed, application logic would also cause the outer SQLTransaction to also rollback. But now we want to change the logic so that, even if there is a failure, the outer transaction should continue executing the remaining sprocs in its sequence, then at the end, since we know there were failures, we rollback the entire SQLTransaction.

The problem is that, at least as it is presently coded, is that if any of the sprocs does a ROLLBACK, the outer SQLTransaction appears to lose its connection, so any subsequent attempt at reusing the transaction fail. Is there a way I can rollback in T-SQL but still maintain the outer SQLTransaction? I was thinking that maybe savepoints might be helpful here, but I don't understand them very well yet.

What complicates this situation is that there is not always an outer transaction, so I can't just remove the T-SQL rollbacks, ie. sometimes a sproc is executed on its own; sometimes in the context of a transaction.

Would switching to TransactionScope make things easier?

Thanks for any suggestions…Mike

Best Answer

Take a look at this knowledgebase entry:

An unexpected exception may occur when a transaction is committed or rolled back after a data source error has occurred

Rolling back a transaction within a stored proc will cause any "outer" transaction in your ADO.NET client to disappear. The only solution is to wrap your Rollback() call in a try/catch block. I don't believe it's possible to maintain the outer transaction if that happens.