简体   繁体   中英

SQL Server stored procedure restore my records if Insert failed

I want to know if there is a way to state rollback the delete if I can not insert.

Please advice.

Something like below.

BEGIN TRAN
Delete from MYTABLE where ID=@ID;

INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME

COMMIT

You can put your two statements into a TRY....CATCH block and only commit if both statements succeed:

BEGIN TRANSACTION
BEGIN TRY
    DELETE FROM dbo.MYTABLE WHERE ID=@ID;

    INSERT INTO dbo.MYTABLE (ID, NAME)
       SELECT @ID, NAME

    -- COMMIT only if both DELETE and INSERT worked ....
    COMMIT TRANSACTION
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

    -- ROLLBACK if either DELETE and INSERT failed ....
    ROLLBACK TRANSACTION
END CATCH

Turn xact_abort on to rollback the transaction on any error.

SET XACT_ABORT ON;
BEGIN TRAN
Delete from MYTABLE where ID=@ID;

INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME

COMMIT TRAN

Here is another way to accomplish what you appear to be trying:

update myTable
set name = @name
where id = @id
BEGIN TRAN

Delete from MYTABLE where ID=@ID;

INSERT INTO MYTABLE (ID, NAME)
SELECT @ID, NAME

if @@error = 0 and @@trancount > 0
    commit
else
    rollback

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM