SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Begin trans with Inserts
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

byka
Starting Member

18 Posts

Posted - 08/12/2014 :  12:36:31  Show Profile  Reply with Quote
Could you help me with writing SQL scripts with insert trans. If one of the inserts failed rollback all previous inserts.
Here what I come up with but I don't think it will work.
SET NOCOUNT ON;

BEGIN TRANSACTION;
BEGIN TRY
Insert 1
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;

END CATCH

BEGIN TRY
Insert 2
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;

END CATCH
BEGIN TRY
Insert 3
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;

END CATCH



IF @@TRANCOUNT > 0

COMMIT TRANSACTION

byka

sz1
Constraint Violating Yak Guru

United Kingdom
441 Posts

Posted - 08/13/2014 :  08:31:06  Show Profile  Reply with Quote
You can use the below to roll back any failure in the tran(s).
SET XACT_ABORT ON;
SET XACT_ABORT OFF;

SET XACT_ABORT ON;
BEGIN TRAN
Code...
COMMIT TRAN
SET XACT_ABORT OFF;

We are the creators of our own reality!
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000