我正在为我的存储过程获取XML,我需要迭代它并根据XML发送电子邮件。
我有另一个存储过程只是为了发送电子邮件:
MailingSystem..SP_SendEmail
@Cc = N'', -- nvarchar(500)
@Bcc = N'', -- nvarchar(500)
@FromEMailAddress = N'', -- nvarchar(500)
@ReplyToEMailAddress = N'', -- nvarchar(500)
@Subject = N'', -- nvarchar(500)
@EmailRecipient = N'', -- nvarchar(500)
@ContentType = N'', -- nvarchar(50)
@Content = N'', -- nvarchar(max)
以下是XML的结构:
DECLARE @XMLData XML =
'<GenericXML>
<GenericEmailsNotification>
<EmailMessage>
<From>John@Google.com</From>
<Recipients>Naomi@Yahoo.com</Recipients>
<CC>Tania@HotMail.com</CC>
<Subject>Follow The Sun </Subject>
<Body>Breathe, breathe in the air. Set your intentions.Dream with care. </Body>
</EmailMessage>
<EmailMessage>
<From>ron@Google.com</From>
<Recipients>Fake@Yahoo.com</Recipients>
<Subject>Second Email is best</Subject>
<Body>Second Email body...</Body>
</EmailMessage>
</GenericEmailsNotification>
</GenericXML>'
我想遍历每个EmailMessage
节点并提取与此节点/电子邮件(主题,发件人,收件人,正文等)相关的数据,并将其发送到负责发送邮件的存储过程
每个XML都可以发送多封电子邮件(如果直到现在还不清楚..)
我该怎么办?有没有办法循环遍历XML元素?
提前致谢
答案 0 :(得分:3)
您可以解析XML
并使用cursor:
DECLARE @XMLData XML =
'<GenericXML>
<GenericEmailsNotification>
<EmailMessage>
<From>John@Google.com</From>
<Recipients>Naomi@Yahoo.com</Recipients>
<CC>Tania@HotMail.com</CC>
<Subject>Follow The Sun </Subject>
<Body>Breathe,breathe in the air.Set your intentions.Dream with care</Body>
</EmailMessage>
<EmailMessage>
<From>ron@Google.com</From>
<Recipients>Fake@Yahoo.com</Recipients>
<Subject>Second Email is best</Subject>
<Body>Second Email body...</Body>
</EmailMessage>
</GenericEmailsNotification>
</GenericXML>' ;
查询:
SELECT [from] = s.c.value('(./From)[1]', 'nvarchar(250)')
,[Recipients] = s.c.value('(./Recipients)[1]', 'nvarchar(250)')
,[CC] = s.c.value('(./CC)[1]', 'nvarchar(250)')
,[Subject] = s.c.value('(./Subject)[1]', 'nvarchar(250)')
,[body] = s.c.value('(./Body)[1]', 'nvarchar(MAX)')
INTO #Emails
FROM @XMLData.nodes('/GenericXML/GenericEmailsNotification/EmailMessage')
AS s(c);
DECLARE cur CURSOR LOCAL FAST_FORWARD FOR
SELECT [from],[Recipients],[CC],[Subject],[body] FROM #Emails;
DECLARE @from NVARCHAR(250),
@recipients NVARCHAR(250),
@cc NVARCHAR(250),
@subject NVARCHAR(250),
@body NVARCHAR(MAX);
OPEN cur;
FETCH NEXT FROM cur INTO @from, @recipients, @cc, @subject, @body;
WHILE @@FETCH_STATUS = 0
BEGIN
-- send email, pass variables to SP call, handle `NULL` with `ISNULL` if needed
-- EXEC MailingSystem..SP_SendEmail @Subject = @subject, ...
SELECT 'Send email in cursor loop:', @from, @recipients, @cc, @subject, @body;
FETCH NEXT FROM cur INTO @from, @recipients, @cc, @subject, @body;
END
CLOSE cur;
DEALLOCATE cur;
的 LiveDemo
强>