0

我们有一个存储过程,它通过具有不同 MS SQL 2008 数据库的链接服务器启动分布式事务。

我们用

  SET XACT_ABORT ON;

并且

  BEGIN TRY / CATCH blocks

围绕事务捕获任何错误并将错误代码和消息返回给调用客户端。

但是,当分布式事务中的命令失败时,似乎 MS DTC 正在接管控制,而我们的 catch 块不能“优雅地”回滚并返回错误消息等。相反,会引发错误:Microsoft Distributed Transaction Coordinator (MS DTC) 已取消分布式事务。(错误 1206)。

有什么方法可以让 catch 块捕获这样的分布式 tx 错误?

4

1 回答 1

0

- -更新 - -

看起来这是一个已知问题,微软不会修复它: http ://connect.microsoft.com/SQLServer/feedback/details/414969/uncatchable-error-when-distributed-transaction-is-aborted

有一种解决方法,但使用 SSIS 调用 SP: http ://social.msdn.microsoft.com/Forums/en/sqlnetfx/thread/02e43cad-ac11-45fa-9281-6b4959929be7


您应该能够使用 XACT_STATE() 回滚事务,并使用 RAISERROR 加上 @@ERROR 为您提供更多详细信息

  SET NOCOUNT ON
  SET XACT_ABORT ON
          BEGIN TRY
      BEGIN TRANSACTION

..代码在这里

  COMMIT TRANSACTION; 

结束尝试
开始捕捉

  DECLARE @errormsg VARCHAR(MAX)
  SET @errormsg = @@ERROR

  -- Test XACT_STATE:
      -- If 1, the transaction is committable.
      -- If -1, the transaction is uncommittable and should 
      --     be rolled back.
      -- XACT_STATE = 0 means that there is no transaction and
      --     a commit or rollback operation would generate an error.

  -- Test whether the transaction is uncommittable.
  IF (XACT_STATE()) = -1
  BEGIN
      ROLLBACK TRANSACTION;
  END;

  -- Test whether the transaction is committable.
  IF (XACT_STATE()) = 1
  BEGIN
      COMMIT TRANSACTION;   
  END;

  RAISERROR(@errormsg, 16, 1)

结束捕获

于 2012-12-10T16:29:01.483 回答