Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit to wrapping every sql/stored proc invocation in a transaction?

The following code executes one stored procedure. The stored procedure has only one command in it. Is there any benefit to wrapping everything in a transaction, even it only has one SQL statement in it (or one stored proc that has only one sql statement)?

In the sample code below, if the delete fails, it fails. There is nothing else to be rolled back (it seems). So why is everything wrapped in a transaction anyhow?

using (ITransactionManager transMan = repository.TransactionManager())
using (IController controller = repository.Controller())
{
    transMan.BeginTransaction();
    try
    {
        //DELETE FROM myTable where Id=@id
        controller.Delete(id);
        transMan.CommitTransaction();
    }
    catch
    {
        transMan.RollbackTransaction();
        throw;
    }
}
like image 609
MatthewMartin Avatar asked Dec 13 '25 07:12

MatthewMartin


1 Answers

You don't really lose much by wrapping it in a transaction (as a lightweight transaction would be used), and if your add more logic to your business layer then you already have working transaction management.

This code will work well with nested transactions as well, whereas if you did not use a transaction at this level, you could lose some of the benefits depending on how the code and stored procedure were structured.

Another possibility is that the stored procedure may change and have multiple statements - again, you would still have working transaction management in place.

I would keep it.

like image 155
Oded Avatar answered Dec 14 '25 21:12

Oded