SQL Server transaction and rollback

Source: Internet
Author: User

If you have to be careful when you want to perform data churn in production, you can use transactions to verify in advance whether your own SQL is what you expect. Especially if there is a problem with the where condition of the update, the new record will exceed the expected range. As the following statement, a hurry I almost put cartid = 678417 Forget, if in production implementation impact is big.

BEGIN TRANSACTIONUpdateCartitemSetDeleted=0 whereCartid= 678417  andModifiedDate> '2014-08-07'Select *  fromCartitemwhereCartid= 678417 Order  byModifiedDatedescROLLBACK TRANSACTION

The following statement implements the statement between Begin Tran and commit Tran, either if an error occurs,

 set  xact_abort on  -- -if the key is not set to ON, the default is off in SQL, then only the Transact-SQL statement that generated the error is rolled back; set to on to roll back the entire transaction  begin  tran  t1 -- -start a transaction  update  Cartitem set  deleted=  0  where  cartid =  Span style= "font-weight:bold; Color: #800000 ">678417  and  modifieddate    " 2014-08-07  "  
Commit Tran T1  ---commit a transaction

Try, Catch for a transaction

BEGINTRYBEGIN TRANSACTION     Insert  intoDbo.areaValues('1111')    Insert  intoDbo.areaValues('2222')    Select 1/0    Insert  intoDbo.areaValues('333')   COMMITENDTRYBEGINCATCHIF @ @TRANCOUNT > 0     ROLLBACK  DECLARE @ErrMsg nvarchar(4000),@ErrSeverity int  SELECT @ErrMsg =error_message (),@ErrSeverity =error_severity ()RAISERROR(@ErrMsg,@ErrSeverity,1)ENDCatch
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.