SQL Mail仅向查询中指定的用户发送电子邮件

时间:2019-02-22 02:40:00

标签: sql tsql sql-server-2016

我有大约1个月的SQL经验,我想根据查询条件向客户发送电子邮件。我面临的挑战是,电子邮件应仅发送给查询中显示的用户电子邮件。以下是数据示例。我不知道应该如何设置基于查询的自动电子邮件。任何帮助将不胜感激!

我的查询看起来像这样

select *
from [Tbl]
where [Date Certificate is Expiring] 
Between getdate()-372 AND getdate()-371

输出:

用户ID |电邮|日期证书即将过期

注意:我无权访问Visual Basic,SSRS,SSIS或数据库引擎和dbMail以外的任何其他工具

1 个答案:

答案 0 :(得分:0)

请先创建数据库邮件配置文件,然后将其放入以下查询中:

DECLARE @MailRecipients NVARCHAR(MAX);
SELECT @MailRecipients = STUFF((
    SELECT DISTINCT ';' + t.Email 
    FROM [Tbl] t 
    WHERE t.[Date Certificate is Expiring] BETWEEN GETDATE()-372 AND GETDATE()-371 
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)'),1,1,'')
;

IF COALESCE(@MailRecipients,'') <> ''
BEGIN
    EXEC msdb.dbo.sp_send_dbmail
            @profile_name = ..., -- <-- you have to create DBMailProfile first
            @recipients = @MailRecipients,
            @subject = 'Email about expiring stuff',
            @body_format = 'HTML',
            @body = 'Hi there, your something is expired',
            @importance = 'Normal' 
END