【问题标题】:rollback whole txn when any of the insert statement fails in stored procedure当存储过程中的任何插入语句失败时回滚整个 txn
【发布时间】:2015-07-21 09:21:01
【问题描述】:

我有一个存储过程,其中有两个不同表的两个插入语句。

create procedure p_multiple_insert
(
// variable declaration
)
declare @temp int = 0;
begin try
    begin 
    // insert statement for TABLE1
        set @temp = 1;
    if(@temp = 1)
        begin
            // insert statement for TABLE2
        end
    end
end try
begin catch
// insert into error table error_number() & error_message()
end catch

如果第一个插入语句块发生错误,@temp = 0。所以第二个插入块没有执行,数据也没有插入到 TABLE1 中。

但是如果在插入 TABLE2 时发生错误,我该如何回滚我的整个事务。我的意思是回滚第一个插入语句。

【问题讨论】:

标签: sql sql-server sql-server-2008 stored-procedures


【解决方案1】:

我的更改是大写:

create procedure p_multiple_insert
(
-- variable declaration
)
declare @temp int = 0;

BEGIN TRANSACTION

begin try
    -- insert statement for TABLE1
        set @temp = 1;
    if(@temp = 1)
        begin
            -- insert statement for TABLE2
        end
    end

    COMMIT TRANSACTION

end try
begin catch

    ROLLBACK TRANSACTION

    -- insert into error table error_number() & error_message()
end catch
  1. 从头开始交易
  2. 在 try 块结束时提交
  3. 回滚 catch 块中的所有内容

我的“Standard-Catch-Block”总是这样:

    DECLARE @errmsg NVARCHAR(MAX)
    SELECT  @errmsg = 'Error executing dbo.StoredProcName: ' 
                         + COALESCE(ERROR_MESSAGE(),'No Message from SQL Server')
    RAISERROR(@errmsg,16,1)
    ROLLBACK TRANSACTION

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    相关资源
    最近更新 更多