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

前端 未结 1 796
执念已碎
执念已碎 2021-01-13 10:28

Using SQL 2012 & getting XML passed into a stored procedure that must take that input & write a row to the table for each of the items that is in a section of the XM

1条回答
  •  离开以前
    2021-01-13 11:08

    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 
    (
        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

    0 讨论(0)
提交回复
热议问题