将xml密钥值对导入sql server?

时间:2014-05-09 05:29:54

标签: sql-server xml ssis

我下面的XML数据代表一行,但似乎无法将其导入sql server而不完全重写xml文件,看起来就像最底层的第二个代码块。我有第一种格式的数千个小xml文件,我需要开始处理并导入到sql表中。理想情况下,如果我不使用某些自定义脚本来重写xml,我认为我可以导入临时表并使用数据透视或转置将属性连接到单元格中。

<ping>
<feed Scale="4.0" resolution="67.58859099656746">
<beta name="my_misc_beta" totalRecords="1">
<row>
<column>
 <key>CUSTOMER ID</key>
 <value>123456</value>
 </column>
<column>
 <key>CUSTOMER NAME</key>
 <value>Johnys Bike Shop</value>
 </column>
<column>
 <key>REGION NAME</key>
 <value>Cool Area</value>
 </column>
<column>
 <key>CUSTOMER CATEGORY</key>
 <value>Bike Shop</value>
 </column>
<column>
 <key>CUSTOMER DESCRIPTION</key>
 <value>coolest bike shop</value>
 </column>
<column>
 <key>CUSTOMER STATUS</key>
 <value>Current</value>
 </column>
<column>
 <key>CUSTOMER CONTACT</key>
 <value>johnny@bikeshop.net</value>
 </column>
 </row>
 </beta>
 </feed>
 </ping>

下面的这个xml很容易使用ssis导入到sql server并循环遍历目录。但我不得不手工重写这个以进行测试。是否有一种方法可能使用c#或其他语言来获取内部文本并将其写入ssis中的元素标记等。比较两个xml文档,您将看到上述代码不会导入到一行。

<ping>
<feed Scale="4.0" resolution="67.58859099656746">
<beta name="my_misc_beta" totalRecords="1">
<row>
<column>
 <CUSTOMER_ID>123456</CUSTOMER_ID>
 <CUSTOMER_NAME>Johnys Pedal Shop</CUSTOMER_NAME>
 <REGION_NAME>Cool Area</REGION_NAME>
 <CUSTOMER_CATEGORY>Bike Shop</CUSTOMER_CATEGORY>
 <CUSTOMER_DESCRIPTION>coolest bike shop</CUSTOMER_DESCRIPTION>
 <CUSTOMER_STATUS>Current</CUSTOMER_STATUS>
 <CUSTOMER_CONTACT>johnny@bikeshop.net</CUSTOMER_CONTACT>
 </column>
 </row>
 </beta>
 </feed>
 </ping>

1 个答案:

答案 0 :(得分:0)

不了解SSIS中的XML功能,但您可以使用常规查询执行所需的操作。

首先,您需要使用nodes() Method (xml Data Type)row节点上粉碎XML,以便为XML中的每个row获取结果中的一行。

然后使用value() Method (xml Data Type)提取所需的列值。您可以按column数字获取值,但在获取值之前检查谓词中的key值会更安全。

select T.X.value('(column[key/text() = "CUSTOMER ID"]/value/text())[1]', 'int') as CustomerID,
       T.X.value('(column[key/text() = "CUSTOMER NAME"]/value/text())[1]', 'nvarchar(100)') as CustomerName,
       T.X.value('(column[key/text() = "REGION NAME"]/value/text())[1]', 'nvarchar(100)') as RegionName,
       T.X.value('(column[key/text() = "CUSTOMER CATEGORY"]/value/text())[1]', 'nvarchar(100)') as CustomerCategory,
       T.X.value('(column[key/text() = "CUSTOMER DESCRIPTION"]/value/text())[1]', 'nvarchar(100)') as CustomerDescription,
       T.X.value('(column[key/text() = "CUSTOMER STATUS"]/value/text())[1]', 'nvarchar(100)') as CustomerStatus,
       T.X.value('(column[key/text() = "CUSTOMER CONTACT"]/value/text())[1]', 'nvarchar(100)') as CustomerContact
from @XML.nodes('/ping/feed/beta/row') as T(X)

SQL Fiddle