XACT_Abort = 关于 Try Catch 的问题

XACT_Abort = ON issue with Try Catch

我有这段脚本:

Create Table AA (ID int identity(1,1), Col1 varchar(10))
Create Table BB (ID int identity(1,1), Col1 varchar(10))
GO
Create proc p6
as
insert into AA
(Col1)
Values('')

GO

Create Trigger [dbo].[TR_AA] on [dbo].[AA]
After insert
As
--Set XACT_Abort off
Select 1/0
GO

Begin Try
Begin Tran

Select @@TRANCOUNT

exec p6

Commit Tran
End Try
Begin Catch
  insert into BB(Col1)Values('')
  Select * from AA
  --Select XACT_STATE()

  Rollback Tran
End Catch

Select Count(*) from AA

GO

当我 运行 此代码时,我收到此错误:

The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.

我已经知道导致此问题的原因。

例子只是一个例子。但是我在触发器中有很多业务逻辑,我无法将它们移出。

所以一种解决方法是将 Set XACT_Abort off 放在 触发。但是,通过这样做,我们覆盖了 SQL 处理触发器错误的默认行为。

我的问题是,如果我这样做会不会给系统带来任何问题?

除了剥离触发器逻辑之外的任何其他解决方案将不胜感激。

如果你想让你的交易保持活跃,XACT_ABORT = OFF 应该会有所帮助。

但是设置 XACT_ABORT = OFF 并不能保证交易在所有情况下都会继续。这取决于错误的严重性。

When SET XACT_ABORT is OFF, in some cases only the Transact-SQL statement that raised the error is rolled back and the transaction continues processing. Depending upon the severity of the error, the entire transaction may be rolled back even when SET XACT_ABORT is OFF.

XACT_ABORT = OFF 的另一个问题是,现在您的错误处理和持久化数据的过程在具有不同 XACT_ABORT 设置的代码中是不同的。

编辑

这些链接可能会有帮助。

Why TRY CATCH does not suppress exception in trigger

Ignoring errors in Trigger