TSQL:触发器中的 Try-Catch 事务

TSQL: Try-Catch Transaction in Trigger(TSQL:触发器中的 Try-Catch 事务)
本文介绍了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 事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)