Sending Email in SQL Server 2008 R2

浪子不回头ぞ 提交于 2019-12-02 12:25:14

I reckon Inside your procedure you could create a Temp table/Table Variable and populate it with the emails you want to send email to.

Once you have all the emails in a table then you could concatenate the email addresses with ; and store it to a variable and pass that variable as a parameter to @recipients parameter of msdb.dbo.sp_send_dbmail proc.

Something like this...

Say you have populated a table variable called Emails inside your procedure

DECLARE @Emails TABLE(Email NVARCHAR(1000))
INSERT INTO @Emails VALUES
('aaa@aaa.com'),('bbb@aaa.com'),('ccc@aaa.com')  --<-- Three emails you want to send email

Concatenation of emails

DECLARE @Email_List NVARCHAR(MAX);   --<-- Variable to store emails List

SELECT @Email_List = STUFF((SELECT ';' + Email [text()]
                            FROM @Emails
                            FOR XML PATH(''),TYPE)
                            .value('.','NVARCHAR(MAX)'),1,1, '')                   
FROM @Emails e 

-- Test SELECT @Email_List
-- RESULT:  aaa@aaa.com;bbb@aaa.com;ccc@aaa.com

Now pass this variable to @recipients parameter

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