Sending Email in SQL Server 2008 R2

柔情痞子 提交于 2019-12-02 16:44:54

问题


I am tasked with a feature to send e-mail reminders to employees in my company if they haven't completed an attestation form via an intranet Web application.

I was thinking of writing a stored procedure that gets called in a nightly database job (SQL Server 2008 R2). The proc would select employee e-mail address values and loop through them via cursor, so that for each e-mail found an e-mail is sent using msdb.dbo.sp_send_dbmail.

The concern I have is that this is for a large company and tens of thousands of e-mail could go out nightly. Is there a way to mitigate performance concerns when sending out such a volume of e-mail? Or at the tens of thousands of level it shouldn't be a concern?


回答1:


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'


来源:https://stackoverflow.com/questions/22025419/sending-email-in-sql-server-2008-r2

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