SQL 2012 - iterate through an XML list (better alternative to a WHILE loop)

邮差的信 提交于 2019-12-01 06:10:57

If you need to do to something that requires a loop (for example, you want to send email to each recipient, than you can use a cursor:

declare cur cursor local fast_forward for
    select
        s.c.value('(text())[1]', 'nvarchar(max)') as SendTo,
        m.c.value('(MyMsg/text())[1]', 'nvarchar(max)') as MyMsg,
        m.c.value('(MsgTime/text())[1]', 'nvarchar(max)') as MsgTime
    from @XML_In.nodes('MyXML') as m(c)
        outer apply m.c.nodes('SendToList/SendTo') as s(c)

open cur
while 1 = 1
begin
    fetch cur into @SendTo, @MyMsg, @MsgTime
    if @@fetch_status <> 0 break

    --=======================================
    -- do what you need here 
    --=======================================
end
close cur
deallocate cur

If you just want to insert rows into some table, you can do this in one simple insert:

insert into <Your table>
(
    SendTo, MyMsg, MsgTime
)
select
    s.c.value('(text())[1]', 'nvarchar(max)') as SendTo,
    m.c.value('(MyMsg/text())[1]', 'nvarchar(max)') as MyMsg,
    m.c.value('(MsgTime/text())[1]', 'nvarchar(max)') as MsgTime
from @XML_In.nodes('MyXML') as m(c)
    outer apply m.c.nodes('SendToList/SendTo') as s(c)

sql fiddle demo

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