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 XML that is passed to the stored procedure. The XML looks like:
<MyXML>
<MyMsg>My Text Message</MyMsg>
<MsgTime>2013-09-25 10:52:37.098</MsgTime>
<SendToList>
<SendTo>John</SendTo>
<SendTo>James</SendTo>
<SendTo>Rob</SendTo>
<SendTo>Pete</SendTo>
<SendTo>Sam</SendTo>
</SendToList>
</MyXML>
The output of the stored procedure should be 5 rows inserted into a table (one for each SendTo
above), and each having the same value in the MyMsg
and MsgTime
fields in that table.
I can get the count of the number of SendTo
and can get the XML SendToList
but I don't know how to iterate through it to do the inserts.
I can use the following SQL to get what's in the XML.
SELECT
x.value('(/MyXML/MyMsg)[1]', 'VARCHAR(1024)'),
x.value('(/MyXML/MsgTime)[1]', 'DATETIME'),
@max = x.query('<e> { count(/MyXML/SendToList/SendTo) } </e>').value('e[1]','int'),
@mlst = x.query('/MyXML/SendTo')
FROM @XML_In.nodes('//MyXML') i(x)
Currently, I'm using variables and a WHILE
to loop through the items in the SendToList, but I know there's got to be a better way.
SELECT @msgTo= @XML_In.value('(/MyXML/SendToList/SendTo[position()=sql:variable("@cnt")])[1]','VARCHAR(100)')
The above gets me the value of each item in the SendToList.
If I select the variable @mlst, I can see the structure of the XML that I need to loop through.
<SendToList>
<SendTo>John</SendTo>
<SendTo>James</SendTo>
<SendTo>Rob</SendTo>
<SendTo>Pete</SendTo>
<SendTo>Sam</SendTo>
</SendToList>
Even though the WHILE
works, it's doing one insert right after the other. I was thinking that the methods available should be able to do it all instead of looping but I don't know enough about using them to do what I need to do.
Would appreciate any help or suggestions.