发送电子邮件的SQL Server 2008触发器

时间:2014-09-30 13:36:54

标签: sql-server triggers

有谁知道为什么这不起作用?它是一个触发器,用于检查插入和更新时字段的值,并从违规行发送一个带有id列值的电子邮件。

ALTER TRIGGER [dbo].[DB]
ON [dbo].[table]
AFTER INSERT, UPDATE AS
BEGIN
IF EXISTS(SELECT 1 FROM inserted WHERE value = 5)
   BEGIN
      EXEC msdb.dbo.sp_send_dbmail
        @recipients = 'me@derp.com', 
        @profile_name = 'MailProfile',
        @subject = 'DB.dbo.table trigger', 
        @body = '',
        @execute_query_database = 'DB',
        @query = 'USE DB SET NOCOUNT ON SELECT id FROM dbo.table WHERE value = 5';
   END
END

问题似乎是sp_send_dbmail函数中的@query。当我手动尝试触发它时,我收到以下错误;

No row was updated.
The data in row x was not committed.
Error Source: .Net SqlClient Data Provider.
Error Message:  Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
Correct the errors and retry or press ESC to cancel the change(s).

当我删除@execute_query_database和@query并向@body var添加一些纯文本时,触发器工作,我收到一封电子邮件。

我也尝试将@query值更改为非常简单的值,例如SELECT "Test" as test但这并没有帮助。

我对触发器完全陌生,所以如果问题很明显......请道歉:)

1 个答案:

答案 0 :(得分:0)

你需要分号:

@query = 'USE DB; SET NOCOUNT ON; SELECT id FROM dbo.table WHERE value = 5;';