SQL Server Transaction Processing (1)

Source: Internet
Author: User

1. It is best to have only one transaction for a stored procedure; multiple transactions consume both resources and are prone to errors;

2. When creating a transaction and ending a transaction, you 'd better have the following judgment:

Code
IF @ TRANCOUNT = 0
BEGIN -- only if @ TRANCOUNT is 0, we do TRAN in TRAN
BEGIN TRANSACTION
SET @ TransactionIsOurs = 1
END
IF @ TransactionIsOurs = 1
BEGIN
COMMIT TRANSACTION
-- SET @ TransactionIsOurs = 0
END
IF @ TransactionIsOurs = 1 AND @ TRANCOUNT> 0
ROLLBACK TRANSACTION

 

3. If the transaction is very long, you can add several more errors at the appropriate position:

Code
IF @ Error <> 0
BEGIN
Raiserror (50002, 16, 1, n'applycheckedobjectsstage ', n'spapplycheckedobjectsstage', 10, n' checked Agence stage ', @ strerrorparm) with log
Set @ returncode =-1000
Goto exit_label
End

 

Note: @ error must be directly followed by the SQL statement to be judged, and other statements cannot be separated between them, because @ error always gets the latest execution result, so it is best to use try... catch...

Code
Use adventureworks;
Go
Begin transaction;

Begin try
-- Generate a constraint violation error.
Delete from Production. Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER () AS ErrorNumber,
ERROR_SEVERITY () AS ErrorSeverity,
ERROR_STATE () as ErrorState,
ERROR_PROCEDURE () as ErrorProcedure,
ERROR_LINE () as ErrorLine,
ERROR_MESSAGE () as ErrorMessage;

IF @ TRANCOUNT> 0
Rollback transaction;
End catch;

IF @ TRANCOUNT> 0
Commit transaction;
GO

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.