|
Can I start a transaction outside of a TRY...CATCH block, and either commit the transaction, or roll it back, within the TRY...CATCH block?
(comments are locked)
|
|
Yes, you can. Just make sure that you check for @@trancount before attempting to rollback transaction in the catch block. Here is the sample: The above will produce something like this in the results window: The transaction is rolled back due to the above error. Oleg Hmm, I read the question differently from you. I assumed the update TSQL was to be outside the TRY too. May delete my answer if I have misunderstood ... :-/
Jul 22 '11 at 08:44 AM
Fatherjack ♦♦
Of course it goes without saying that try/catch block does not work for Sev 10 errors because it is too mild and of course does not work for Sev 20 cause those are too harsh. The good news is that it is by design and the majority of the standard errors such as constraint violations, invalid PK, dup in the key etc are all Sev 16 :)
Jul 22 '11 at 08:51 AM
Oleg
Although it works, I feel it makes more sense to put all your work inside a try/catch if you are using them. It just seems more sensible to me, if you are doing the whole error management, then use it for everything.
Jul 25 '11 at 12:36 AM
WilliamD
@WilliamD Yes, of course. This type of thinking is caused by the influence of DEV work. For example, if my sample had to be a C# snippet then I could not possibly instantiate a transaction and declare variables in the try block and then expect them to still be visible in the catch because their scope would be limited to try block, so they would be out of scope in the catch :) Welcome back from your long trip!
Jul 25 '11 at 08:30 AM
Oleg
You can also check the XACT_STATE() to see if the transaction is active and valid
Jul 25 '11 at 02:59 PM
Scot Hauder
(comments are locked)
|
|
Works like a charm. Try it out...
(comments are locked)
|
|
I dont think that syntax would be supported. Try it on a test environment and see if it works. What are you trying to achieve? I cant think of a reason you would want to do this. The TRY is where the data update is attempted and then the CATCH is where you handle any issues encountered with completing the data change. @Fatherjack It looks like you are thinking about something more complex than what the OP is asking. It is perfectly normal to begin tran and place commit tran in the try block and rollback in the catch (after the @@trancount is checked).
Jul 22 '11 at 08:42 AM
Oleg
Yeah, I think you are right !
Jul 24 '11 at 11:45 PM
Fatherjack ♦♦
(comments are locked)
|

