How to loop and parse xml parameter in sql server stored procedure

后端 未结 1 868
一整个雨季
一整个雨季 2020-12-05 05:52

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:

相关标签:
1条回答
  • 2020-12-05 06:13

    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! :-)

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