Is there any side effect if select statements are wrapped in BEGIN TRAN … COMMIT?
-
06-03-2021 - |
Question
I am working on a rather old .NET project and have introduced some new features (on top) that have generated the following side-effect: all generated SELECTs (or groups of) are wrapped in BEGIN TRAN ... COMMIT
statements.
This sounds silly, but getting rid of this requires a lot of changes and I cannot afford to do so. My assumption is this basically means a small overhead for each group of SELECTs (roundtrips between application and SQL Server for BEGIN TRAN and COMMIT).
I am wondering if there is more to this (extra locking?).
Question: Is there any side effect if select statements are wrapped in BEGIN TRAN ... COMMIT?
Solution
The answer depends on what isolation level your .NET project is setting when it accesses SQL Server.
If it's READ COMMITTED
(the default), then there's not really any additional overhead (other than the additional BEGIN TRAN
and END TRAN
statements being executed). You might think additional information would be written to the transaction log, but transactions don't really "begin" until something happens that needs to be logged. I've written about this here: Transactions Don't Start At BEGIN TRAN
If you're using the SERIALIZABLE
isolation level, you could get burned by the fact that those SELECT
queries will hold the locks they take for the duration of the transaction. This could be happening without you realizing it if you're using TransactionScope
in your .NET project, since that uses SERIALIZABLE
by default (see my blog post for a demo: TransactionScope Considered Annoying).
I'd say all in all, if the default isolation level is being used, there's not much downside to leaving things the way you've described. You'll want to be careful about the isolation levels though.