我曾经在我的数据库中有触发器,当某些列被更新时,它使用cursors
/发送电子邮件。sp_send_dbmail
有人告诉我这不是最佳实践,所以我创建了一个名为 EmailNotify 的新表,其中包含收件人、主题、正文等列。因此,触发器现在将我要发送的电子邮件插入到该表中。
我想创建一个每隔几分钟运行一次的作业来检查这个表和电子邮件。下面的项目是我想出的,但在这种情况下可以使用游标吗?该表是否应该包含一个已发送字段,以便我知道我发送了哪些行?我可以在光标内更改它吗?还是建议事后截断表格?
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