[英]How do I insert output from xml.nodes() into a table?
I am new to sql server and I am trying to insert rows into a database from XML documents. 我是sql server的新手,我试图从XML文档中将行插入数据库。 I have done some research and managed to get XML into a rowset using the XML nodes function. 我做了一些研究,并设法使用XML节点函数将XML转换为行集。 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)
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)
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. 您需要将SELECT
语句的输出传递给要在其中填充数据的表的INSERT
语句。
Suggestions : 意见建议 :
int
assuming that both fields should represent numbers. 您可以将用于id和age节点的数据类型从nvarchar(10)更改为int
假设两个字段都应表示数字。 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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.