在sql server中插入后发送邮件

时间:2014-09-24 15:57:41

标签: sql-server

我有一个名为regis_tbl的表,在表中我有一个名为的字段 电子邮件。我想做的是我想立即向用户发送电子邮件给用户 插入表格。请问我该怎么做

1 个答案:

答案 0 :(得分:1)

首先,您需要设置数据库邮件 - 如果您还没有这样做,这个问题可能会有所帮助:

Scripting setup of database mail

然后你需要一个触发器:

CREATE TRIGGER dbo.whatever

ON dbo.wherever FOR INSERT 如 开始     SET NOCOUNT ON;

IF EXISTS (SELECT 1 FROM inserted WHERE speed > 100)
BEGIN
    EXEC msdb.dbo.sp_send_dbmail
      @recipients = 'whoever@yourcompany.com', 
      @profile_name = 'default',
      @subject = 'Someone was speeding', 
      @body = 'Yep, they sure were.';
END

END GO

现在,您可能会说您希望插件中的数据实际包含在电子邮件中。你的第一个倾向是声明一些局部变量并从插入中分配它们 - 这不起作用,因为你的触发器可以响应多行插入。所以正确的方法是:

CREATE TRIGGER dbo.whatever

ON dbo.wherever FOR INSERT 如 开始     SET NOCOUNT ON;

DECLARE @body NVARCHAR(MAX) = N'';

SELECT @body += CHAR(13) + CHAR(10) + RTRIM(some_col) FROM inserted;

IF EXISTS (SELECT 1 FROM inserted WHERE speed > 100)
BEGIN
    EXEC msdb.dbo.sp_send_dbmail
      @recipients = 'whoever@yourcompany.com', 
      @profile_name = 'default',
      @subject = 'At least one person was speeding', 
      @body = @body;
END

END GO

所有人都说,我不是从触发器发送电子邮件的忠实粉丝。即使数据库邮件使用服务代理也是异步的,我更倾向于填充队列表,并且有一个后台线程,并发送所有相应的电子邮件。关于这一点的两件好事是:

you minimize the potential delays in committing the outer transaction that fired the trigger - the more complicated your logic in the trigger, the slower you make that process.
since it is probably not essential that the e-mail is sent the microsecond the row is inserted, you can easily fluctuate the timing of the background process - this avoids having to check the table very minute, all day, when very few times it will ever have to actually do anything.
  1. 您最小化了提交触发触发器的外部事务的潜在延迟 - 触发器中的逻辑越复杂,您执行该过程的速度就越慢。 由于电子邮件可能不是必需的,微秒插入行,你可以很容易地调整后台处理的时间 - 这样就可以避免必须在非常短的时间内查看表格永远不得不做任何事情。 正如@goodeye指出的那样,保持这个过程是分开的可以防止进程的电子邮件部分中的错误干扰原始DML(在他们的情况下,sp_send_dbmail的无效参数 - 我无意中建议 - 阻止了插入)。 / LI>