尝试使用此代码每行发送一封电子邮件时,我会在每个相关行收到一封电子邮件。但是,每封电子邮件仅包含第一行的值:
DECLARE @BCC VARCHAR(MAX) = ''
DECLARE @TO VARCHAR(300) = 'a@gmail.com'
DECLARE @CC VARCHAR(300) = ''
DECLARE @Sender VARCHAR ( 300 ) = (SELECT ParameterValue FROM EmailParameters (NOLOCK) WHERE ParameterLabel = 'Sender')
DECLARE @Subject VARCHAR(150) = (Select [Subject] FROM [EmailTemplates] WHERE EmailTemplateID = 10)
DECLARE @Body NVARCHAR(MAX) = (Select EmailTemplate FROM [EmailTemplates] WHERE EmailTemplateID = 10)
DECLARE @IP VArchar(15) = (SELECT TOP(1) c.local_net_address FROM sys.dm_exec_connections AS c WHERE c.local_net_address IS NOT NULL) --Get IP Address
DECLARE @Date Datetime
DECLARE @Database sysname
DECLARE @RestoreResult NVARCHAR (50)
DECLARE @DbccResult NVARCHAR (50)
DECLARE @ID INT
SET @Date = getdate()
Set @Body = REPLACE(@Body, '@IP', @IP)
Set @Subject = REPLACE(@Subject, '@Sender', @Sender)
Set @Subject = REPLACE(@Subject, '@Date', @Date)
DECLARE BackupCursor CURSOR FOR
SELECT [Database], RestoreResult, DbccResult, ID
FROM BackupTestResults_Alerting
WHERE SentFlag = 0;
-- Open cursor
OPEN BackupCursor;
-- Get first row
FETCH NEXT FROM BackupCursor
INTO @Database, @RestoreResult, @DbccResult, @ID;
-- While there is data
WHILE (@@fetch_status = 0)
BEGIN
Set @Body = REPLACE(@Body, '@Database', @Database)
Set @Body = REPLACE(@Body, '@RestoreResult', @RestoreResult)
Set @Body = REPLACE(@Body, '@DbccResult', @DbccResult)
INSERT INTO [EmailQueue]
SELECT 10,
@Body,
@To,
@Cc,
@Bcc,
@Subject,
0
EXEC SDP.dbo.usp_Email_Send
print @dbccResult
-- Grab the next record
FETCH NEXT FROM BackupCursor
INTO @Database, @RestoreResult, @DbccResult, @ID;
END
-- Close cursor
CLOSE BackupCursor;
-- Release memory
DEALLOCATE BackupCursor;
替换功能动态替换出现在每封电子邮件的 html 正文中的变量。打印命令正确显示了我要为其发送电子邮件的每一行。但是,每封电子邮件中仅显示第一行的值。
如何确保将每一行的正确值传递给每封电子邮件?
编辑: 谢谢大家的信息回复。我将包含有关我的总体目标的更多信息。
我有自动备份测试,并希望在备份测试失败时收到电子邮件提醒。目前,我可以通过将备份测试结果记录到结果表,将任何失败的结果复制到警报表,然后从警报表中读取作业并向我发送任何失败的电子邮件来实现这一点。主要限制是这项工作一次只能捕获一行,因此需要多次运行以防出现多个失败结果。
我想找到一个更优雅的解决方案,其中电子邮件警报作业可以作为最后一步合并到备份测试作业中。