views:

1028

answers:

3

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

A: 

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.

Matt Hamilton
A: 

I would suggest that you consider placing your outer transaction in a stored procedure as well so that you maintain all of your nesting within TSQL (use EXEC to call other stored procs). SQL Server is a surprisingly rich development / data management environment and will permit you to manage your transactions in ways that ADO handles clumsily. Keep in mind, too, that it is almost always more efficient to gang a bunch of SQL together in a stored proc than it is to make multiple calls over an ADO connection.

Mark Brittingham
A: 

It might interest you to look at IMPLICIT_TRANSACTION Basically with this you can change the transaction dependent mode of your stored procedure. This is an easier solution in many cases.

Learning