Proper way to use a transaction around multiple inserts or updates

前端 未结 3 657
不知归路
不知归路 2020-12-24 09:42

What is the proper way to test for insert/update failures and rollback this transaction if there are any? I don\'t think what I have will work since my inserts/updates are 3

3条回答
  •  春和景丽
    2020-12-24 10:12

    If you put SET XACT_ABORT ON before you start transaction, in case of an error, rollback will be issued automatically.

    SET XACT_ABORT ON
    
    begin transaction
    
    INSERT INTO TableA (id) VALUES (1)
    INSERT INTO TableB (id) VALUES (1)
    UPDATE TableC SET id=1 WHERE id=2
    
    commit transaction
    

    If you want to do rollback yourself, use try .. catch block.

    begin transaction
    
    begin try
    
      INSERT INTO TableA (id) VALUES (1)
      INSERT INTO TableB (id) VALUES (1)
      UPDATE TableC SET id=1 WHERE id=2
    
      commit transaction
    
    end try
    
    begin catch
      raiserror('Message here', 16, 1)
      rollback transaction
    end catch
    

提交回复
热议问题