简体   繁体   English

如果插入失败,SQL Server存储过程将还原我的记录

[英]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: 您可以将两个语句放入TRY....CATCH块中,只有在两个语句都成功时才提交:

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. 打开xact_abort以在任何错误上回滚事务。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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