Begin Tran, commit Tran, and rollback Tran usage

Source: Internet
Author: User

SQL Server 2005/2008 provides begin Tran, commit Tran, and rollback Tran to use transactions. Begin Tran indicates that the transaction starts, commit Tran indicates that the transaction is committed, and rollback Tran indicates that the transaction is rolled back. The usage is as follows:

-- ===================================================== ======
-- Author: cynimoon
-- Create Date: 2009-10-09
-- Description: sample stored procedure
-- ===================================================== ======
-- Exec test_proc '文 ',' including history, geography, politics ', 'politics', and '文'

Create procedure [DBO]. [test_proc]

@ A_name nvarchar (20), -- name of Table

@ A_remark nvarchar (4000), -- remarks in Table

@ B _name nvarchar (20), -- table B Name

@ B _remark nvarchar (4000) -- remarks in Table B

As

Begin try

Begin tran

-- Insert data into Table

Insert into [DBO]. [A]

([A_name]

, [A_remark])

Values

(@ A_name

, @ A_remark)

-- Insert data into Table B

Insert into [DBO]. [B]

([A_id]

, [B _name]

, [B _remark])

Values

(@ Identity -- return the last inserted id value

, @ B _name

, @ B _remark)

Commit tran

End try

Begin catch

Rollback tran

Insert into [DBO]. [errorlog]

([El_procedure] -- Name of the exception Stored Procedure

, [El_operatetime]) -- reports the exception time

Values

('Test _ proc'

, Convert (datetime, getdate (), 20 ))

End catch

Note: 1. @ identity is used to return the last inserted id value.

2. I added a special exception record table to rollback Tran to determine the time when the exception occurred and the name of the stored procedure reporting the exception.

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.