如何从SQL Server数据库使用sp_send_dbmail程序发送多封电子邮件(How to

2019-10-19 22:50发布

我有程序,这导致一个数据表包含3个电子邮件,proposal_Type,计数(MatchestoEmail)的匹配是基于proposal_type。 现在我要发送通知邮件到“电子邮件”,说明他们有这么多数量的基础上Proposal_Type比赛。 该过程的输出数据将是这样的。

Emails           Prop_Type   Matches

abc@gmail.com     1            3 

abc@gmail.com     2            4

def@gmail.com     3            2              

我想要的邮件被收件人,其余两列,与一些额外的文本电子邮件的正文。 plz帮助我。

谢谢

Answer 1:

编辑

这应该工作

create proc [dbo].[SendProposalReport] as   
declare rscursor cursor read_only
for 
select Emails, Prop_Type, count(Matches) as Matches  from proposals
group by Emails, Prop_Type

    declare @Emails            nvarchar (100)
    declare @Prop_Type    int
    declare @Maches    int

open rscursor
fetch next from rscursor into @Emails,@Prop_Type,@Maches
while @@fetch_status=0
    begin

         EXEC msdb.dbo.sp_send_dbmail
        @recipients = @Emails,
        @subject = 'Example Email',
        @body = 'write your message here',
        @profile_name = 'ExampleProfile',

        @attach_query_result_as_file = 1        

    fetch next from rscursor into @Emails,@Prop_Type,@Maches
end
close rscursor
deallocate rscursor


Answer 2:

光标会解决你的问题:

DECLARE <yourvariables>
DECLARE emailCursor CURSOR FOR
SELECT emails, prop_type, matches FROM <yourtable>
OPEN emailCursor
FETCH NEXT FROM emailCursor INTO @email, @prop_type, @matches
WHILE @@FETCH_STATUS = 0
BEGIN
   SET @BODY = '<body text>' + @prop_type + '<more text>' + @matches
   EXEC msdb.dbo.sp_send_dbmail
   @recipients = @email,
   @subject = '<subject>',
   @body = @BODY
   FETCH NEXT FROM emailCursor INTO @email, @prop_type, @matches
END
CLOSE emailCursor
DEALLOCATE emailCursor


文章来源: How to send multiple emails from sql server database using sp_send_dbmail procedure