views:

1760

answers:

4

Imagine the follwoing scenario: I am using Sql Server 2005. I have a transaction that is calling, among others Sql statements, a stored procedure that also has a transaction inside. The outer transaction sometimes fails and it is rolledback after the stored procedure is called and commited successfully. My question is, does the storedProcedure's transaction rollback too?

A: 

Hi,

Yes the stored procedure will be rolled back.

Here is the overall flow of your code:

BEGIN TRY

    BEGIN TRANSACTION

    EXEC SotredProcedureName

    --Do some other activity

    COMMIT TRANSACTION
END TRY
BEGIN CATCH

    --IF an error occurs then rollback the current transaction, which includes the stored procedure code.
    ROLLBACK TRANSACTION

END CATCH

Cheers, John

John Sansom
+1  A: 

With a nested transaction, a commit does not write any changes to disk, except for the top level transaction. A rollback, however works regardless of the level of the transaction, so yes, it will roll the inner transaction back.

MatthieuF
+2  A: 

Absolutely yes, the top level transaction will own all the data changes until it is committed or rolled back.

However I would encourage you to think carefully about the transaction model. The more such scenarios exist in your system the greater your exposure to locking issues. Also the computational expense of the procedure increases.

It's remarkable how often, when rationalising SQL, I find transactions have been implemented where they just aren't required. I encourage you (and anyone working with transactions) to think carefully about why you are using them in each context and what would happen were the transaction not implemented. Just my 2c worth!

CodeBadger
A: 

I've tried with begin tran and commit inside the stored procedure say usp_test. exec these sp with some other query as below

update x set name='xxx' select * from x---contains 'xxx' begin tran update x set name='yyy' select * from x---contains 'yyy' exec usp_test select * from x---contains 'zzz' inside the sp rollback tran

while executing the above query name in x table must be 'xxx' its not 'zzz' since the first begin tran rollbacked even the sp tran commit. So, First begin tran own the data changes.

Jayaprabha