Simple example of a stored procedure with transactions in SQL Server

Source: Internet
Author: User

First look at a concept:

A database transaction is a series of operations performed as a single logical unit of work, either completely or Transaction. Then adding a transaction to the stored procedure ensures that all the SQL code in the transaction is either fully executed or not executed at all.

For a simple stored procedure with a transaction:

Begin
Set NOCOUNT on; --Does not return the number of rows affected
Set Xact_abort on; --Use stored procedure to execute transaction need to turn on Xact_abort parameter (default is OFF)

Delete from table1 where name= "--delete data sql1
BEGIN Tran Tran1--Start a transaction tran1
Delete from table1 where name= "--delete data sql2
Save Tran Tran2--Saves a transaction point tran2
Update table2 set name= ' where id= '--Modify data Sql3

If @ @error <>0--Determine if there is an error in modifying the data (@ @error represents a nonzero error code that returns the last statement (that is, SQL3) with the @ @ERROR, and returns 0 without errors)

Begin
Rollback TRAN Tran2--rollback TRANSACTION to tran2 restore point
Commit Tran Tran1--Commit TRANSACTION Tran1
End
Else-commits the transaction without error Tran1
Commit Tran Tran1--Commit TRANSACTION Tran1
End

If Sql3 execution fails, it is rolled back to the creation of the transaction tran2 (which is equivalent to SQL1 and sql2 execution).

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.