SQL Server XACT_ABORT with exclusion

后端 未结 3 1309
南旧
南旧 2021-01-21 16:55

I have a larger stored procedure which utilizes several TRY/CATCH blocks in order to catch and log individual errors. I have also wrapped a transaction around the entire content

3条回答
  •  爱一瞬间的悲伤
    2021-01-21 17:07

    You can try something like below ,which ensures you log the operation.This takes advantage of the fact that table variables dont get rollbacked..

    Psuedo code only to give you idea:

    create table test1
    (
    id int primary key
    )
    
    create table logg
    (
    errmsg varchar(max)
    )
    
    
    
    declare @errmsg varchar(max)
    
    set xact_abort on
    begin try
    begin tran
    insert into test1
    select 1
    
    insert into test1
    select 1
    
    commit
    end try
    
    begin catch
    set @errmsg=ERROR_MESSAGE()
    select @errmsg as "in block"
    if @@trancount>0
    rollback tran
    
    end catch
    set xact_abort off
    
    
    select @errmsg as "after block";
    
    insert into logg
    select @errmsg
    
    
    select * from logg
    

提交回复
热议问题