如何获取xml列的一部分,并将其作为SQL中自己的结果集返回?
我的数据库中有一个xml文件,如下所示:
<main>
<data>
<rows>
<_items>
<columns>
<values>
<keyvaluepairs>
<keyvaluepairofstringstring>
<key>EVENT</key>
<value>Wedding</value>
</keyvaluepairofstringstring>
<keyvaluepairofstringstring>
<key>DETAIL</key>
<value>Smith-Wesson</value>
</keyvaluepairofstringstring>
</keyvaluepairs>
</values>
</columns>
<columns>
<values>
<keyvaluepairs>
<keyvaluepairofstringstring>
<key>EVENT</key>
<value>Reunion</value>
</keyvaluepairofstringstring>
<keyvaluepairofstringstring>
<key>DETAIL</key>
<value>Class of 1996</value>
</keyvaluepairofstringstring>
</keyvaluepairs>
</values>
</columns>
<columns>
<values>
<keyvaluepairs>
<keyvaluepairofstringstring>
<key>EVENT</key>
<value>Pie-throwing contest</value>
</keyvaluepairofstringstring>
<keyvaluepairofstringstring>
<key>DETAIL</key>
<value>Cherry pies</value>
</keyvaluepairofstringstring>
</keyvaluepairs>
</values>
</columns>
</_items>
</rows>
</data>
</main>
我希望将“行”作为结果集返回:
EVENT NAME
Wedding Smith-Wesson
Reunion Class of 1996
Pie-throwing contest Cherry pies
...etc...
我使用方法described here来查询单个值,但这还不足以获取我真正需要的所有数据。
我正在使用SQL Server 2008。
编辑:为了澄清,这个xml包含在一行中。例如,要返回上面的xml,我会输入
select my_xml_column from my_table;
答案 0 :(得分:2)
试试这个:
select X.N.value('(keyvaluepairofstringstring/value[../key = "EVENT"])[1]', 'varchar(100)') as EVENT,
X.N.value('(keyvaluepairofstringstring/value[../key = "DETAIL"])[1]', 'varchar(100)') as NAME
from YourTable as T
cross apply T.XMLCol.nodes('/main/data/rows/_items/columns/values/keyvaluepairs') as X(N)
顺便说一句,我必须修复你的XML。那里有一些缺少的结束标记。