如何在 SQL Server 2012 中针对自定义错误消息创建 SQL 代理警报?

Dan*_*ing 6 t-sql sql-server-2012 sql-server-agent alerts raiserror

我希望在抛出自定义错误消息时通知操作员。我的理解是我需要向 sys.messages 添加一条消息,然后我可以RAISERROR或者THROW那个错误 ID。在消息 ID 上创建警报并将其设置为发送给操作员应该会创建这些通知。

我在消息 ID 50005 上创建了 SQL 代理警报,并使用以下 T-SQL 创建消息:

EXEC sp_addmessage @msgnum = 50005,
          @severity = 16,
          @msgtext = N'%s';
GO
Run Code Online (Sandbox Code Playgroud)

然后,如果我执行这个:

RAISERROR (50005, -- Message id.
       16, -- Severity,
       1, -- State,
       N'My custom message');
THROW 50005, 'My custom message', 1;
GO
Run Code Online (Sandbox Code Playgroud)

我从RAISERROR和得到以下输出THROW

Msg 50005, Level 16, State 1, Line 68 我的自定义消息

但是,当我查看警报的历史记录时,它显示它尚未触发,并且操作员未收到电子邮件更新。

我的代理警报如下所示:

代理警报设置

编写警报脚本会生成以下内容:

USE [msdb]
GO
EXEC msdb.dbo.sp_update_alert @name=N'Alert DBA on custom errors', 
    @message_id=50005, 
    @severity=0, 
    @enabled=1, 
    @delay_between_responses=0, 
    @include_event_description_in=1, 
    @database_name=N'', 
    @notification_message=N'', 
    @event_description_keyword=N'', 
    @performance_condition=N'', 
    @wmi_namespace=N'', 
    @wmi_query=N'', 
    @job_id=N'00000000-0000-0000-0000-000000000000'
GO
EXEC msdb.dbo.sp_update_notification @alert_name=N'Alert DBA on custom errors', @operator_name=N'My Operator', @notification_method = 1
GO
Run Code Online (Sandbox Code Playgroud)

为了您的方便,如果您尝试重新创建我的问题,这将帮助您从 sys.messages 中删除:

sp_dropmessage @msgnum = 50005; 
GO
Run Code Online (Sandbox Code Playgroud)

Kin*_*hah 5

请参考创建用户自定义事件

默认情况下,严重性低于 19 的用户定义消息在发生时不会发送到 Microsoft Windows 应用程序日志。因此,严重性低于 19 的用户定义消息不会触发 SQL Server 代理警报。

所以你的信息应该是

EXEC sp_addmessage @msgnum = 50005,
      @severity = 1,  -- Informational messages that return status information or report errors that are not severe. The Database Engine does not raise system errors with severities of 0 through 9.
      @msgtext = N'%s';
GO
Run Code Online (Sandbox Code Playgroud)

当您使用 时THROW,它默认为不触发警报的严重性 16。

RAISERROR (50005, -- Message id.
       1, -- Severity,
       1, -- State,
       N'My custom message') with log;
Run Code Online (Sandbox Code Playgroud)
USE [msdb]
GO

/****** Object:  Alert [Alert DBA on custom errors]    Script Date: 1/22/2016 3:17:22 PM ******/
EXEC msdb.dbo.sp_add_alert @name=N'Alert DBA on custom errors', 
        @message_id=50005, 
        @severity=0, 
        @enabled=1, 
        @delay_between_responses=0, 
        @include_event_description_in=0, 
        @database_name=N'AdventureWorks2012_test', 
        @category_name=N'[Uncategorized]', 
        @job_id=N'00000000-0000-0000-0000-000000000000'
GO
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

此外,请确保使用@delay_between_responses合理的值,以免收件箱中充斥着电子邮件。

另外,请参阅我对使用用户定义的消息和警报监视 SQL Server 数据文件中的可用空间的回答。