TSQL: Try-Catch Transaction in Trigger(TSQL:触发器中的 Try-Catch 事务)
问题描述
我正在尝试使用 Microsoft Server 2005 将 try-catch 语句放入触发器中.
I am trying to put a try-catch statement inside a trigger using Microsoft Server 2005.
BEGIN TRANSACTION
BEGIN TRY
--Some More SQL
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF (XACT_STATE()) = -1
BEGIN
ROLLBACK TRANSACTION;
END;
END CATCH
问题是,如果 try-catch 块捕获到某些内容,我不希望触发器失败.目前,我收到错误事务在触发器中结束.批处理已中止."如果交易失败.如何让触发器优雅地失败?
The problem is that I don't want the trigger to fail if something is caught by the try-catch block. At the moment, I am getting the error "The transaction ended in the trigger. The batch has been aborted." if the transaction fails. How can I get the trigger to fail gracefully?
此外,如果我删除事务,我会收到错误事务在触发器中注定失败.批处理已中止.".
Additionally, if I remove the transaction, I get the error "Transaction doomed in trigger. Batch has been aborted.".
BEGIN TRY
--Some More SQL
END TRY
BEGIN CATCH
return
END CATCH
有什么办法可以解决这个问题吗?
Is there any way around this?
推荐答案
根据我的经验,在触发器的 try catch 中捕获的任何错误都会回滚整个事务;您也许可以使用保存事务.我认为您需要查看更多 sql"中发生的情况,并确定您是否可以围绕它编写 case/if 语句来阻止错误.
In my experience any error caught in a try catch in a trigger will rollback the entire transaction; you may be able to use a save transaction. I think you need to look at whats happening in "Some more sql" and determine if you can write case / if statements around it to stop the error.
根据您正在做的事情,您可以做的是使用 save交易并在catch中捕获它
What you may be able todo depending on what you are doing is use a save transaction and capture that in the catch
在你的代码中是这样的
SAVE TRANSACTION BeforeUpdate;
BEGIN TRY
--Some More SQL
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION BeforeUpdate;
return
END CATCH
这篇关于TSQL:触发器中的 Try-Catch 事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TSQL:触发器中的 Try-Catch 事务


- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01