簡體   English   中英

如果插入失敗,SQL Server存儲過程將還原我的記錄

[英]SQL Server stored procedure restore my records if Insert failed

我想知道如果我無法插入,是否有辦法說明刪除刪除。

請指教。

像下面的東西。

BEGIN TRAN
Delete from MYTABLE where ID=@ID;

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

COMMIT

您可以將兩個語句放入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

打開xact_abort以在任何錯誤上回滾事務。

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

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

COMMIT TRAN

這是完成您似乎嘗試的另一種方法:

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