2

I'm using TransactionScope in my C# code. I will try to simplify as much as I can .

public void ProcessStrings(...)
{
    ...
    using (TransactionScope transactionScope = new TransactionScope())
    {
        ...
        if(someCondition)  
        {   
            try
            {  
                DeleteSomeStrings(...);
            }
            catch(Exception ex)
            {
                //log error
                ...
                throw;
            }
        }

        ...

        try
        {
            UpdateSomeStrings(...);
        }
        catch(Exception ex)
        {
            //log error
            ...
            throw;
        }

        ...

        transactionScope.Complete();
    }
    ...
}

The DeleteSomeStrings and UpdateSomeStrings methods call two stored procedures through ADO.NET. I need to use explicit transaction handling into these stored procedures as well because they are also called from other contexts:

CREATE PROCEDURE [dbo].[DeleteSomeStrings]
...
--parameter list
...
AS
BEGIN TRY

    BEGIN TRAN
    ...
    COMMIT TRAN
END TRY

BEGIN CATCH
    ...
    ROLLBACK 
    ...
    RAISERROR(...)
END CATCH

and the second one has a similar structure:

CREATE PROCEDURE [dbo].[UpdateSomeStrings]
...
--parameter list
...
AS
BEGIN TRY

    BEGIN TRAN
    ...
    COMMIT TRAN
END TRY

BEGIN CATCH
    ...
    ROLLBACK 
    ...
    RAISERROR(...)
END CATCH

The problem is when DeleteSomeStrings succeeds and UpdateSomeStrings fails, the data that was processed in DeleteSomeStrings still gets committed. It looks like the TransactionScope is ignored in this scenario. I would expect everything to be rolled back. Is this the normal behavior and if so why?

Cristian Rusanu
  • 452
  • 5
  • 15
  • When you are executing the first stored procedure, try using `rowsAffected = cmd.ExecuteNonQuery();` if rowsAffexted is Zero, no point in executing the second SP – user2526236 Apr 17 '15 at 15:55
  • have a look a this post: http://stackoverflow.com/questions/15431285/call-multiple-sql-server-stored-procedures-in-a-transaction – fabricio Apr 17 '15 at 15:57

1 Answers1

1

Managed to get it work by using SqlTransaction instead of TransactionScope and passing the same connection and transaction to the command objects that were used to execute the two stored procedures. It seams TransactionScope cannot be used in this scenario. Thanks for your comments.

Cristian Rusanu
  • 452
  • 5
  • 15