SQLTransaction Question...
I am writing an application that writes to two separate SQL Servers so I use two separate SQLConnection objects. Problem is, I would like to use a nested transaction so that if the parent transaction is rolled back then the inner transaction is also rolled back as below:
-----------------------------------------------------------
Declare Connection1
Declare Connection2
Open Connection1
Open Connection2
Begin Transaction For Connection1
Update database for Connection1
Begin Transaction For Connection2
Update database for Connection2
Commit Transaction For Connection2
Rollback Transaction For Connection1 (I want this to rollback the data for Connection1 and Connection2)
-----------------------------------------------------------
Clearly the above does not work due to the transactions being associated with different connection objects. Is there any way this can be achieved in VB.NET?
Re: SQLTransaction Question...
i dont know, may be it's too late but
Mendhak: i think your code is not right, why ? because the finally block is executed anyway whether there is an error or not. so in the case of exception the transaction will be rolledback then trying to execute the commit in the finally block (which will be executed anyway). the finally block itself will raise exception. so i think the commit should be moved from the finally to the last line of the try block. so that if it can't commit then rollback
i know i am late , but i was searching for some information on the forums and i mbumbed out with this thread.
one other thing. Mendhak is far more advanced than me, so i think it is just a typing mistake. :)
rgds
Re: SQLTransaction Question...
Ah, that was from my early VB days ;)
Although this thread is more than a year old and completely irrelevant, I think I'd correct that post like this:
VB Code:
Dim trans As SqlTransaction = conn.BeginTransaction()
Dim trans2 As SqlTransaction = conn2.BeginTransaction()
Try
'Your operations
trans.Commit()
trans2.Commit()
Catch sqlx as SQLException
'handle it
trans.Rollback()
trans2.Rollback()
Finally
End Try
This way any error will roll back both transactions. Of course, there may have to be checks in place to rollback the other transaction which might not even occur, so a boolean If-Then-Else can be placed there.