I want to write a stored procedure that accept an XML parameter, parsing it's elements and inserting them in a table. This is my XML:
I want to loop in that parameter(such as a foreach in C#), retrieving each person, then parsing it's data(ID,NAME,LASTNAME) inserting them in a table that has 3 fields.
How can do that?
1) Duplicate the stored procedure and add the FOR XML to the return statement(not pretty but works). 2) Have a second stored procedure call the non-XML version and just return the results using FOR XML . 3) Build the XML in the SELECT statement of the stored procedure.
Try this statement:
SELECT
Pers.value('(ID)[1]', 'int') as 'ID',
Pers.value('(Name)[1]', 'Varchar(50)') as 'Name',
Pers.value('(LastName)[1]', 'varchar(50)') as 'LastName'
FROM
@YourXml.nodes('/Employees/Person') as EMP(Pers)
This gives you a nice, row/column representation of that data.
And of course, you can extend that to be the second part in an INSERT statement:
INSERT INTO dbo.YourTargetTable(ID, Name, LastName)
SELECT
Pers.value('(ID)[1]', 'int') as 'ID',
Pers.value('(Name)[1]', 'Varchar(50)') as 'Name',
Pers.value('(LastName)[1]', 'varchar(50)') as 'LastName'
FROM
@YourXml.nodes('/Employees/Person') as EMP(Pers)
Done - no loops or cursors or any awful stuff like that needed! :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With