我正在尝试将 XML 文件导入 SQL Server 数据库。请查看代码和 xml 文件。提前致谢。
我试图用谷歌搜索很多页面,但所有页面都只处理一个孩子(或如何称呼它)。
但在我真正的 xml 中,结构就像
:1x supplier --> multiple orders --> multiple customers --> multiple products.
我们需要创建一个存储过程,当我们获取 XML 文件时将调用该存储过程。
再次感谢彼得
SQL 代码:
DROP TABLE #TEST
CREATE TABLE #TEST
(CUSTID VARCHAR(10),CUSTNAME VARCHAR(50),PRODUCT VARCHAR(500))
INSERT INTO #TEST(CUSTID,CUSTNAME,PRODUCT)
SELECT
x.orders.query('order/customer/cust_id').value('.', 'VARCHAR(10)'),
x.orders.query('order/customer/name').value('.', 'VARCHAR(50)'),
x.orders.query('order/product_lines/product/supplier_prod_num').
value('.','VARCHAR(500)')
FROM
(SELECT CAST(x AS XML)
FROM OPENROWSET(
BULK '\\test\Test.xml',
SINGLE_BLOB) AS T(x)) AS T(x)
CROSS APPLY
x.nodes('order_batch/orders/order/product_lines/product') AS x(orders)
select * from #test
要测试的 XML 文件:
<order_batch>
<order_header>
<doc_format_ver>1.0</doc_format_ver>
<originating_software>
<software_name>test</software_name>
<software_ver>2.0</software_ver>
</originating_software>
</order_header>
<supplier>
<cp_supplier_id>93</cp_supplier_id>
<name>supname</name>
<address_line_1>address_line_1</address_line_1>
<address_line_2>address_line_1</address_line_2>
</supplier>
<orders>
<order o_count="1">
<customer>
<cust_id>7240</cust_id>
<name>CustNamek</name>
<address_line_1>address_line_1</address_line_1>
<address_line_2>address_line_1</address_line_2>
</customer>
<order_details>
<date_created>2012-10-08</date_created>
<time_created>05:37:11</time_created>
</order_details>
<product_lines>
<product p_count="1">
<supplier_prod_num>15115</supplier_prod_num>
<qty_type>E</qty_type>
</product>
<product p_count="2">
<supplier_prod_num>010211</supplier_prod_num>
<qty_type>E</qty_type>
</product>
</product_lines>
</order>
<order o_count="2">
<customer>
<cust_id>7238</cust_id>
<name>custname</name>
<address_line_1>address_line_1</address_line_1>
<address_line_2>address_line_1</address_line_2>
</customer>
<order_details>
<supplier_ref>0093513982</supplier_ref>
<delivery_date>2012-10-08</delivery_date>
<special_instructions />
</order_details>
<product_lines>
<product p_count="1">
<supplier_prod_num>6748</supplier_prod_num>
<qty_type>E</qty_type>
</product>
<product p_count="2">
<supplier_prod_num>6744</supplier_prod_num>
<qty_type>E</qty_type>
</product>
</product_lines>
</order>
</orders>
</order_batch>