如何捕捉分布式事务中的“严重错误”?

时间:2020-02-06 03:00:50

标签: sql-server error-handling try-catch distributed-transactions

在分布式事务中,尝试插入违反唯一键的值时会发生“严重错误”。如何捕获“严重错误”?

示例查询1

SET XACT_ABORT ON
BEGIN DISTRIBUTED TRAN
    BEGIN TRY
        INSERT INTO [LINKEDSERVER].[DB].[SCHEMA].[TABLE] VALUES(THE VALUES Violation of UNIQUE KEY)
    END TRY
COMMIT TRAN
BEGIN CATCH
    ROLLBACK TRAN
    PRINT ERROR_MESSAGE()
END CATCH

结果1

*Msg 0, Level 11, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.*

示例查询2

INSERT INTO [LINKEDSERVER].[DB].[SCHEMA].[TABLE] VALUES(THE VALUES Violation of UNIQUE KEY)

结果2

Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'XXX'. Cannot insert duplicate key in object '[SCHEMA].[TABLE]'. The duplicate key value is (XXX).

经过测试的环境

From : Microsoft SQL Server 2017 (RTM) - 14.0.1000.169 (X64) on Windows 10 Pro 10.0
To : Microsoft SQL Server 2016 (RTM) - 13.0.1601.5 (X64) on Windows Server 2012 R2 Standard

From : Microsoft SQL Server 2012 - 11.0.2100.60 (X64) on Windows NT 6.2
To : Microsoft SQL Server 2017 (RTM) - 14.0.1000.169 (X64) on Windows 10 Pro 10.0

0 个答案:

没有答案