我需要每天向大约20个收件人发送电子邮件,我建立一个有两列的临时表
EMAIL_BODY
EMAIL_ADDRESS
每天表中最多有50行
我想循环使用此表并执行sp_send_email
EXEC msdb.dbo.sp_send_dbmail
@Profile_name = 'DBA',
@recipients = @email_address,
@body = @Email_Body,
@subject = 'Test Email'
有没有办法在没有游标的情况下做到这一点?
任何一个例子的链接都会受到赞赏,我已经搜索过但找不到这样的例子。我相信这是一个非常普遍的过程。
答案 0 :(得分:1)
--Email Campaign.
declare @HtmlModel varchar(max)
declare @HtmlBody varchar(max)
SELECT @HtmlModel = EmailBody
FROM EmailCampaigns
WHERE ID = 1
--a different process will have created an awesome looking well formed html with our known
--placeholders for [FirstName] [LastName] [Phone] [Email] that might ber substituted for individualization
--PRINT @HtmlModel;
SET @HtmlBody=''
declare
@mailID int,
@id int,
@first varchar(64),
@last varchar(64),
@phone varchar(64),
@email varchar(64)
declare c1 cursor for
--################################
SELECT ID,
ISNULL(FirstName,'Friend') AS FirstName,
ISNULL(LastName,'') AS LastName,
ISNULL(Phone,''),
ISNULL(Email ,'')
--the row_number is so that if i put your name in the database five times, you only get a single email.
FROM (
select ROW_NUMBER() over (partition by email order by email,len(firstname)desc,len(lastname)desc ) AS RW, *
from RawContacts
where email <> '') x
WHERE RW = 1
--this WHERe stays in place until we are ready to go LIVE with the email.
and email IN('lowell@somedomain.com','otherReviewer@somedomain.com')
--################################
open c1
fetch next from c1 into @id,@first,@last,@phone,@email
While @@fetch_status <> -1
begin
SET @HtmlBody = REPLACE(@HTMLModel,'[FirstName]',@first)
SET @HtmlBody = REPLACE(@HtmlBody,'[LastName]', @last)
SET @HtmlBody = REPLACE(@HtmlBody,'[Phone]', @phone)
SET @HtmlBody = REPLACE(@HtmlBody,'[Email]', @email)
--EXEC msdb.dbo.sp_send_dbmail
@Profile_name = 'Database Mail Profile Name',
@recipients=@email,
@subject = 'Our non profits Call for Volunteers',
@body = @HtmlBody,
@body_format = 'HTML',
@mailitem_id = @mailID OUTPUT
--@body_format = 'TEXT'
INSERT INTO CampaignRecipients(Campaign,RawContactID,MailSentID,MailSentDate)
SELECT 1,@id,@mailID,GETDATE()
fetch next from c1 into @id,@first,@last,@phone,@email
end
close c1
deallocate c1
GO
答案 1 :(得分:0)
您可以尝试找到here找到的解决方案。
答案 2 :(得分:0)
我认为此代码示例会有所帮助:
while (@count <=(select COUNT(*) from @table))
begin
select top 1 @Recepient_Email=Emp_Email,@mailBody=body from @table where ID=@count
EXEC msdb.dbo.sp_send_dbmail
@profile_name='Profile1',
@recipients=@Recepient_Email,
@subject = 'This is subject of test Email'
@body = @mailbody,
@body_format = 'HTML'
set @count =@count +1
END