如何从XACT_ABORT捕获/保存日志

时间:2018-08-02 13:39:34

标签: sql sql-server

我具有以下结构:

DECLARE @TranName VARCHAR(20) = 'TransName';
SET XACT_ABORT ON

BEGIN TRANSACTION @TranName
SET XACT_ABORT, NOCOUNT ON;
BEGIN TRY
    INSERT INTO #Test VALUES(1); -- For example

    COMMIT TRANSACTION @TranName
END TRY
BEGIN CATCH
    ROLLBACK TRANSACTION @TranName
    INSERT INTO LogErrors VALUES(@TranName, CAST(ERROR_LINE() as VARCHAR) + ' - ' + ERROR_MESSAGE(), GETDATE());
END CATCH

但是我只是从ERROR_MESSAGES()结构中捕获TRY/CATCH,我也需要从XACT_ABORT中捕获消息/日志。

我在Log Viewer上看到以下陈述:

Executed as user: SERVER/sqlprod. Unspecified error occurred on SQL Server. Connection may have been terminated by the server. [SQLSTATE HY000] (Error 0). The step failed.

我需要捕获此消息并将其保存在我的表LogErrors上,可以吗?

1 个答案:

答案 0 :(得分:1)

请参阅本文,了解如何阅读事件日志

Reading the SQL Server log files using TSQL

您可以调整样本以完成您想要的