Group Department并使用DBMail发送电子邮件

时间:2017-12-30 04:16:50

标签: sql-server tsql

我在SQL Server

中使用DBMAIL发送通知时需要帮助

向部门发送电子邮件,并提供相应的部门信息。         例如,向it@gmail.com发送电子邮件通知应仅包括IT部门信息,不应包括销售部门信息。         并且it@gmail.com有两条记录,因此两者都应合并为一封电子邮件,而不是表格中每条记录的多封电子邮件。 ##

Expected Output : "it@gmail.com" should receive Department "IT" and Name ( A, B)
            "sales@gmail.com" should receive Department "Sales" and Name(C)
            "service@gmail.com" should receive Department "Service" and Name (D)

Create table #temp( ID Int Identity(1,1), Name varchar(50), Department varchar(25), Email varchar(1000))

insert into #temp ( Name , department, Email)
    Values('A','IT','it@gmail.com'),
    ('B','Sales','sales@gmail.com'),
    ('C','Testing','it@gmail.com'),
    ('D','Service','service@gmail.com')

    DECLARE @xml NVARCHAR(MAX)
    DECLARE @body NVARCHAR(MAX)

    SET @xml = CAST(( SELECT Name AS 'td','',Department AS 'td'
    FROM  #Temp 
    FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))

    SET @body ='<html><body><H3>Email notification to respective department</H3>
    <table border = 1> 
    <tr>
    <th> Name </th> <th> Department </th> </tr>'    

    SET @body = @body + @xml +'</table></body></html>'
    declare @emaillist varchar(max) 

    EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Notification', 
    @body = @body,
    @body_format ='HTML',
    @recipients = @emaillist,
    @subject = 'E-mail in Tabular Format' 

1 个答案:

答案 0 :(得分:0)

由于您的目标是发送多封电子邮件,并且每封电子邮件都需要调用函数,因此您可能需要循环播放。这是循环的骨架,可以帮助解决这种情况:

-- Pull email addresses into a table so that we can loop through each one:
DECLARE @Emails TABLE (
    ID INT IDENTITY(1, 1),
    Email VARCHAR(1000)
);

INSERT INTO @Emails (Email)
    SELECT DISTINCT Email
    FROM #temp;

-- Go through each email address, build the body, and send the email:
DECLARE @curID INT = 1;
DECLARE @maxID INT = (SELECT MAX(ID) FROM @Emails);
DECLARE @curEmail VARCHAR(1000);

WHILE @curID <= @maxID BEGIN

    SET @curEmail = (SELECT Email FROM @Emails WHERE ID = @curID);

    -- Insert code to build email body for the current email address and send email here

    SET @curID += 1;
END

您应该能够使用与您提供的示例非常相似的代码来构建正文并自行发送电子邮件。只需确保将XML查询限制为每个循环迭代的单个电子邮件地址。