Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How do I do a sql transaction where it rolls back if something fails?

Posted on 2014-03-05
2
Medium Priority
?
325 Views
Last Modified: 2014-03-15
Hi,

I have a large sql query running that inserts records into multiple tables but what I want to do is have the whole thing roll back if an insert fails for some reason.


What would be the correct syntax for doing this transaction?
0
Comment
Question by:jazz__man
2 Comments
 
LVL 11

Assisted Solution

by:HuaMinChen
HuaMinChen earned 1000 total points
ID: 39905859
See this example
USE AdventureWorks2012;
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

Open in new window


This will also work for Update and Insert.
0
 
LVL 70

Accepted Solution

by:
Scott Pletcher earned 1000 total points
ID: 39908125
You must explicitly start a transaction, put all INSERTs within that transaction, and then either commit or rollback the trans.

BEGIN TRY
BEGIN TRANSACTION

INSERT INTO dbo.table1 ( ... )
SELECT ...
FROM ...

INSERT INTO dbo.table2 ( ... )
SELECT ...
FROM ...

...

COMMIT TRANSACTION
END TRY

BEGIN CATCH
IF XACT_STATE() <> 0
    ROLLBACK TRANSACTION
...other error code here, including using ERROR_* functions to get error info...
END CATCH
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Via a live example, show how to shrink a transaction log file down to a reasonable size.

886 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question