views:

39

answers:

2

I have written a transaction like:

    BEGIN TRAN

    UPDATE  [Table1]
    SET [Name] = 'abcd'
    WHERE   [ID] = 1

    UPDATE  [Table2]
    SET [Product] = 'efgh'
    WHERE   [ID] = 10

    UPDATE  [Table3]
    SET [Customar] = 'ijkl'
    WHERE   [ID] = 11

Now I want to rollback if any UPDATE is not success. For example in Table2 if there is no Product with ID=10 the transaction should be rolled back. How to do this?Please note that I am using SQLServer 2000.

+3  A: 

SQL Server 2000. You don't need rollback if you use SET XACT_ABORT ON

SET XACT_ABORT ON --to ensure rollback
BEGIN TRAN -- @@TRANCOUNT + 1

UPDATE  [Table1]
SET [Name] = 'abcd'
WHERE   [ID] = 1
IF @@ROWCOUNT = 0 ROLLBACK TRAN

IF @@TRANCOUNT > 0
BEGIN
    UPDATE  [Table2]
    SET [Product] = 'efgh'
    WHERE   [ID] = 10

    IF @@ROWCOUNT = 0 ROLLBACK TRAN
END

IF @@TRANCOUNT > 0
BEGIN
    UPDATE  [Table3]
    SET [Customar] = 'ijkl'
    WHERE   [ID] = 11

    IF @@ROWCOUNT = 0 ROLLBACK TRAN
END

IF @@TRANCOUNT > 0 COMMIT TRAN
gbn
But SqlServer 2000 does not support try catch.
ANP
@gbn - Is this supported only on SQL 2000 or any higher version too?
Sachin Shanbhag
Still it is not working for me.
ANP
yes, supported on sql server 2005+ but I *really would* recommend using TRY/CATCH on higher versions.
gbn
@ANP: that's because we are not trapping errors but @@rowcount
gbn
@gbn - Thanks.It works fine. But is there any other way so that I can avoid those if condition writing again and again check at only one place?Like @@ERROR we can check?
ANP
@Sachin Shanbhag, @ANP: you can use SET XACT_ABORT ON to avoid @@ERROR checks.
gbn
+1  A: 

Before each UPDATE statement you need to do BEGIN TRAN and after each of your UPDATE statement, you need to do this -

if @@Error > 0
 THEN 
 BEGIN
   ROLLBACK TRAN
 END
Else
 BEGIN
   COMMIT TRAN
 END
Sachin Shanbhag
+1 To compensate for the unexplained downvote
Andomar
@Andomar: not my downvote but would need *per statement* @@error tests. And to test @@rowcount *per statement* for correct answer to what was asked. This construct by itself is useless.
gbn
@Andomar - No problem, But I would like to know if there is any issue while using this @@Error according to you. I really dont know the downside of this.
Sachin Shanbhag
@Sachin Shanbhag: Like gbn says, the questioner wants to detect missing rows, not errors, so `@@error` would always be 0 (looks like the downvoter removed his downvote btw)
Andomar