SQL Server transaction processing rollback transaction

Source: Internet
Author: User

Create a table:

Set Ansi_nulls On
Go
Set Quoted_identifier On
Go
Create   Table   [ DBO ] . [ T1 ] (
[ ID ]   [ Int ]   Not   Null ,
[ C1 ]   [ Nvarchar ] ( 50 ) Null ,
[ C2 ]   [ Datetime ]   Null ,
  Constraint   [ Pk_table1 ]   Primary   Key   Clustered  
(
[ ID ]   ASC
) With (Pad_index =   Off , Statistics_norecompute =   Off , Ignore_dup_key =   Off , Allow_row_locks =   On , Allow_page_locks =   On ) On   [ Primary ]
) On   [ Primary ]

 

Solution (1)


Declare @ Ierrorcount Int  
Set   @ Ierrorcount   =   0
Begin   Tran Tran_2008_10_07

insert into T1 (ID, c1) values ( 1 , ' 1 ' )
set @ ierrorcount = @ ierrorcount + @@ error

insert into T1 (ID, c1) values ( 2 , ' 2 ' )
set @ ierrorcount = @ ierrorcount + @@ error

insert into T1 (ID, c1) values ( ' xxxx3 ' , ' 3 ' )
set @ ierrorcount = @ ierrorcount + @@ error

insert into T1 (ID, c1) values ( 4 , ' 4 ' )
set @ ierrorcount = @ ierrorcount + @@ error

Insert IntoT1 (ID, C1)Values(5,'5')
Set @ Ierrorcount=@ Ierrorcount+@ Error

If   @ Ierrorcount = 0  
Begin
Commit   Tran Tran_2008_10_07
End  
Else
Begin
Rollback   Tran Tran_2008_10_07
End  

 

Solution (2)

Begin Try
Begin   Tran Tran_2008_10_07

Insert IntoT1 (ID, C1)Values(1,'1')

insert into T1 (ID, c1) values ( 2 , ' 2 ' )

insert into T1 (ID, c1) values ( ' xxxx3 ' , ' 3 ' )

insert into T1 (ID, c1) values ( 4 , ' 4 ' )

insert into T1 (ID, c1) values ( 5 , ' 5 ' )

commit Tran tran_2008_10_07
end try
begin catch
raiserror ' error '
rollback Tran tran_2008_10_07
end catch

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.