我有一个名为regis_tbl的表,在表中我有一个名为的字段 电子邮件。我想做的是我想立即向用户发送电子邮件给用户 插入表格。请问我该怎么做
答案 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.