Is it possible to have SQL Server auto rollback your transactions after a certain amount of time to avoid the blocking/locking that is caused? I have been guilty of this in the past and I hear it from many others that it is a common mistake.
For example:
I always use a block such as this When doing deletes/updates.
BEGIN TRAN
--SQL Code Here
ROLLBACK TRAN
COMMIT TRAN
This allows me to see how many rows are affected or perform a select on the data and then I can comment out the ROLLBACK
which will automatically COMMIT
the TRANSACTION
.
However, there is a possibility of the of not having the COMMIT
highlighted/selected which causes the transaction to hang. What I am looking for is a setting such as:
BEGIN TRAN 15 Seconds
--SQL Code Here
ROLLBACK TRAN
COMMIT TRAN
This will only keep the transaction open a max of 15 seconds.
If this is not possible, does anyone have a better workflow for this?
Best Answer
You could create a job that checks for open transactions and kills them if they've been open for a period of time and are causing blocking. But you'd have to be careful with this as you could have a large, necessary transaction that takes a while that you don't want to get killed. Imagine rolling back an index rebuild that's been running for an hour on Standard Edition.
You can use sp_WhoIsActive to find open transactions that are causing blocking, though it'll take a bit of work.
But I would recommend that you don't do this and instead are diligent with your transactions in Management Studio. Any window that I ever started a transaction in gets closed when I am done. And if there's still an open transaction in it, SSMS will warn me about it so that I can commit/rollback.