How do I insert output from xml.nodes() into a table?

廉价感情. 提交于 2019-12-14 03:07:29

问题


I am new to sql server and I am trying to insert rows into a database from XML documents. I have done some research and managed to get XML into a rowset using the XML nodes function. However, I have no idea what to do next. How do I insert this rowset into an existing table with the same column names?

Below is what I have so far, can anyone help with where I go next?

DECLARE @xml xml
SET @xml = 
N'  <Products>
        <Product>
        <id>4</id>
        <name>Amy</name>
        <age>25</age>
        </Product>
        <Product>
            <id>7</id>
            <name>Vicky</name>
            <age>40</age>
        </Product>
    </Products>'

SELECT  doc.col.value('id[1]',      'nvarchar(10)')     id
    ,   doc.col.value('name[1]',    'varchar(100)')     name 
    ,   doc.col.value('age[1]',     'nvarchar(10)')     age 
FROM    @xml.nodes('/Products/Product') doc(col)

回答1:


You need to pass the output of the SELECT statement to the INSERT statement of the table into which you would like the data to be populated.

Suggestions:

  • You can change the datatype used for id and age nodes from nvarchar(10) to int assuming that both fields should represent numbers.

Script:

CREATE  TABLE dbo.mytable
(   
        id      INT         NOT NULL
    ,   name    VARCHAR(30) NOT NULL
    ,   age     INT         NULL
)

DECLARE @xml xml
SET @xml = 
N'  <Products>
        <Product>
        <id>4</id>
        <name>John</name>
        <age>25</age>
        </Product>
        <Product>
            <id>7</id>
            <name>Jane</name>
            <age>40</age>
        </Product>
        <Product>
            <id>6</id>
            <name>Jill</name>
            <age></age>
        </Product>
    </Products>'

INSERT INTO dbo.mytable (id, name, age)
SELECT  doc.col.value('id[1]',      'int')      id
    ,   doc.col.value('name[1]',    'varchar(100)')     name 
    ,   doc.col.value('age[1]',     'int')      age 
FROM    @xml.nodes('/Products/Product') doc(col);

SELECT * FROM dbo.mytable;

Output:

id  name    age
--  ------  ---
4   John    25
7   Jane    40
6   Jill    0



回答2:


You might need this

INSERT INTO YourTableName(Id,name,age)
SELECT
 doc.col.value('id[1]', 'nvarchar(10)') id
,doc.col.value('name[1]', 'varchar(100)') name 
,doc.col.value('age[1]', 'nvarchar(10)') age 
FROM @xml.nodes('/Products/Product') doc(col)



回答3:


INSERT INTO Table
(
col1
, col2
, col3
)
SELECT
 doc.col.value('id[1]', 'nvarchar(10)')
,doc.col.value('name[1]', 'varchar(100)')
,doc.col.value('age[1]', 'nvarchar(10)')
FROM 
    @xml.nodes('/Products/Product') doc(col)


来源:https://stackoverflow.com/questions/10396721/how-do-i-insert-output-from-xml-nodes-into-a-table

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