Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mr_mist
Grunnio
1870 Posts |
Posted - 2004-07-07 : 08:15:35
|
Hmm. I am curious as to what is wrong with my transaction logic here..Take for example this IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE id=OBJECT_ID('tempdb..#tmpErrors')) DROP TABLE #tmpErrorsGOCREATE TABLE #tmpErrors (Error int)create table moo (moo int null)SET XACT_ABORT ONGOBEGIN TRANgoINSERT INTO moo values ('eggcup') -- This produces an errorgoINSERT INTO moo values (1)GOIF @@ERROR<>0 AND @@TRANCOUNT>0BEGINROLLBACK TRANSACTIONENDGOIF @@TRANCOUNT=0 BEGININSERT INTO #tmpErrors (Error) SELECT 1PRINT 'FAILED'BEGIN TRANSACTIONENDELSE: PRINT 'SUCCESS'GOIF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTIONGOIF @@TRANCOUNT>0 BEGINPrint 'succeeded'COMMIT TRANSACTIONEndElse: Print 'failed'GODROP TABLE #tmpErrorsGOselect * from moodrop table mooNow, what I would like to see here, is that select * from moo returning 0 rows. But, instead, it returns the 1 from the row that was INSERTed before my ROLLBACK TRANSACTION.So, my question is, why does my ROLLBACK not do so?One possible assumption is that it is the GO statement causing this not to happen, but, if that is the case, then why does this work..create table moo (moo int null)begin trangoinsert into moo values (1)goROLLBACKselect * from moodrop table moo Essentially, what I am trying to achieve is that if *any* statement within the transaction produces an error, I want the transaction to stop executing and roll back.-------Moo. :) |
|
|
mohdowais
Sheikh of Yak Knowledge
1456 Posts |
Posted - 2004-07-07 : 08:27:46
|
mist, mate...you have got to trap and check the value of the @@ERROR variable after every statement that could potentially fail. It's even safer to store the value of @@ERROR into a local variable, since it is reset after every statement - it really is quite volatile and disappears rather quickly. So your inserts would have to be like this:INSERT INTO #moo VALUES('doodle doo')SELECT @MyError = @@ERRORIF @MyError > 0 BEGIN RAISE all hellENDINSERT INTO #moo VALUES(2)SELECT @MyError = @@ERRORIF @MyError > 0 BEGIN RAISE more hellENDOS |
 |
|
|
mr_mist
Grunnio
1870 Posts |
Posted - 2004-07-07 : 08:45:31
|
| Hmm. I feared as much. Sadly the script that this problem actually relates to is a lot longer than my example. :|Is there no way to get the transaction to bomb out after any error?-------Moo. :) |
 |
|
|
|
|
|
|
|