SQL Server transactions and rollback transactions

Source: Internet
Author: User

 

First:

Declare @ iErrorCount int
Set @ iErrorCount = 0
Begin tran Tran1
Insert into t1 (Id, c1) values (1, '1 ')
Set @ iErrorCount = @ iErrorCount + @ error

Insert into t1 (Id, c1) values ('xx2 ', '2 ')
Set @ iErrorCount = @ iErrorCount + @ error

If @ iErrorCount = 0
Begin
Commit tran Tran1 -- execute a transaction
End
Else
Begin
Rollback tran Tran1 -- roll back the transaction
End

Second:

Begin Try
Begin Tran Tran1
Insert into t1 (Id, c1) values (1, '1 ')
Insert into t1 (Id, c1) values ('xx2 ', '2') -- this sentence produces an error
Commit tran Tran1
END Try
Begin Catch
Raiserror 50005n' error occurred'
Rollback tran Tran1 --- Call ROLLBACK after an error occurs
END Catch

Third:

If the SET XACT_ABORT ON ---- statement produces a running error, the entire transaction is terminated and rolled back.
Begin Tran
Insert into t1 (Id, c1) VALUES (1, '1 ')
Insert into t1 (Id, c1) VALUES ('xx2 ', '2') -- when an error occurs in this sentence, the entire transaction is rolled back.
Commit Tran

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.