Stored procedure using sp_send_dbmail to send emails to multiple recipients queried from database

前端 未结 1 957
南笙
南笙 2021-01-23 04:23

Like the title says, I\'m trying to make a stored procedure used to send emails to addresses stored in the database, often including multiple recipients. I\'ve tried a few appro

相关标签:
1条回答
  • 2021-01-23 04:55

    You can do a query and assign the values to a variable as such:

    DECLARE @myRecipientList varchar(max)
    SET @myRecipientList = (STUFF((SELECT ';' + emailaddress FROM table FOR XML PATH('')),1,1,''))
    

    This will set your @myRecipientLIst to a ";" delimited list of the recipients specified your query.

    You could also do the same sort of idea with a SP, just throw them into a temp/variable table and stuff into a semi colon separated list.

    EDIT:

    Finally to send the mail you could do:

    EXEC msdb.dbo.sp_send_dbmail
      @recipients = @recipientList,
      @subject = @subject,
      @body = @body // ........
    

    COMMENT EDIT:

    based on your original query, your stuff query should look something like this:

    DECLARE @myRecipientList varchar(max)
    SET @myRecipientList = STUFF((SELECT ';' + email FROM emailTable WHERE idNumber = @idNumber FOR XML PATH('')),1,1,'')
    

    The idea behind this is - for every email found in the email table append to @myrecipientList the email found and a semi colon.

    0 讨论(0)
提交回复
热议问题