What is the most elegant way to identify an error into transaction? At this time my code is like:
begin transaction tx1
update ....
insert ....
if @@error = 0
commit
else
rollback
end
This only catch last operation error, in this case errors on insert but not first operation error, in my case, update errors. How can I improve my code?
Have you looked at
TRY/CATCH?http://msdn.microsoft.com/en-us/library/ms175976.aspx
Of course you’ll still only be able to catch the first error that sent you into
CATCHif you do something like this:But you can wrap each operation in its own
TRY/CATCH, e.g.But then I’m not sure what rules you’d want to follow here… do you want the insert to succeed if the update failed? If you want all actions to succeed or fail as a group then you want the first approach where everything is attempted in one
TRY.Also you should look at Erland Sommarskog’s bible on error handling:
http://www.sommarskog.se/error_handling_2005.html