我以前在我的数据库中有触发器,当某些列更新时,使用cursors
/ sp_send_dbmail
发送电子邮件。有人告诉我这不是最佳做法所以我创建了一个名为EmailNotify的新表,其中包含了诸如recepient,subject,body等列。因此,触发器现在会在此表中插入我要发送的电子邮件。
我想创建一个每分钟运行一次的Job来检查这个表和电子邮件。下面的项目是我提出的,但在这种情况下是否可以使用游标?该表是否应包含已发送的字段,以便知道我发送了哪些行?我可以在光标内更改吗?或者是否会建议事后截断表格?
DECLARE @emailSubject AS NVARCHAR(100);
DECLARE @emailRecipients AS NVARCHAR(100);
DECLARE @emailBody AS NVARCHAR(max);
DECLARE cur CURSOR LOCAL READ_ONLY FAST_FORWARD FOR
SELECT
recipients,
subject,
body
FROM
EmailNotify;
OPEN cur
FETCH NEXT FROM cur INTO
@emailRecipients,
@emailSubject,
@emailBody
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'name',
@recipients = @emailRecipients,
@body = @emailBody,
@body_format = 'HTML',
@subject = @emailSubject;
FETCH NEXT FROM cur INTO
@emailRecipients,
@emailSubject,
@emailBody
END
CLOSE cur
DEALLOCATE cur
答案 0 :(得分:2)
我会
EmailSent(DATETIME) = NULL
列EmailSent
变量,并将其设置为GETDATE()
UPDATE <YOURTABLE> SET EmailSent = @EmailSent WHERE EmailSent IS NULL
WHERE EmailSent = @EmailSent
电子邮件您可以使用带有订阅或数据绑定订阅的SSRS报告而不是此作业来完成此操作,但这只是一个偏好问题。在SSRS中格式化更容易,否则您在邮件正文中弄乱了动态HTML。去过那里,不愉快。