I executed the following query in SQL Server 2012:
create table testTransaction
(
id int
name varchar(100)
)
insert into testTransaction values (1,'ABC'),(2,'XYZ')
/* Query1 */
begin try
begin transaction
insert into testTransaction values (3,'FGH')
commit transaction
end try
begin catch
if @@trancount > 0
rollback transaction
end catch
I executed query1 and got an error that the account I was using did not have permission to insert values into that table. In another window, I tried to do a select on testTransaction but the query kept going on and on.
It was then I realized that the previous query I ran in the other window had an open transaction. I went and rolled it back and everything worked fine.
What would have happened if I had closed the window that had the open transaction without rolling it back?
Would the transaction be open till someone manually rolls it back or does SQL server rollback any uncommitted transactions when a window is closed?
Also, how do I find out all the open transactions in a database across any session?
Best Answer
Answering Your Questions
On the premise that most RDBMS function on the basis of the ACID principle, your transaction would be rolled back.
(emphasis mine)
Reference: ACID (Wikipedia)
Closing a window should result in the transaction being rolled back to guarantee the ACID properties of the database transactions.
Closing Query Window in SSMS (actual case)
In SSMS you are presented with a dialog which lets you decide how to react to closing a window:
Forcefully Closing SSMS via Taskmanager (actual case)
When SSMS is terminated via Taskmanager and/or forcefully closed, then the transaction is automatically rolled back.
This can be reproduced with the following steps:
Create the following table in a database
Open up one SSMS and execute the following script:
Open up a second SSMS and execute the following script:
Kill the first SSMS via Task Manager.
Verify that the second script from step 3. does not display any data.
...and as mentioned by J.D. in his linked answer.
The transaction would be rolled back under normal circumstances.
To determine the currently open transactions you could query the
sys.dm_exec_sessions
,sys.dm_exec_connections
,sys.dm_exec_reuqests
and other System Management Views to determine any open transactions in a request or in a session.Example script:
The columns
Session_Open_Tranactions
andRequest_Open_Transaction
would show you the transactions currently still running for any givenSession_ID
.