How to send multiple emails from sql server database using sp_send_dbmail procedure

感情迁移 提交于 2019-12-24 11:40:25

问题


I have procedure which results a data table contains 3 columns Emails,proposal_Type,count(MatchestoEmail) the matches is based on proposal_type. Now I have to send a notification mails to the 'Emails' stating that they have these many number of matches based on Proposal_Type. the procedure output data will be like this.

Emails           Prop_Type   Matches

abc@gmail.com     1            3 

abc@gmail.com     2            4

def@gmail.com     3            2              

I want the mails to be recipient and the remaining two columns to in the Body of the Email with some additional text. plz help me.

Thanks


回答1:


Edited

This should work

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



回答2:


A cursor would solve your problem:

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


来源:https://stackoverflow.com/questions/23194804/how-to-send-multiple-emails-from-sql-server-database-using-sp-send-dbmail-proced

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!