我在表中有一个简单的XML字段,在其节点中存储一个或多个值:
<MultiSelect>
<ItemKey>38</ItemKey>
<ItemKey>36</ItemKey>
</MultiSelect>
如何以这样的方式查询此字段,即将这些值提取到结果中的列?
来源数据:
RowKey Format
-----------------
1 <MultiSelect><ItemKey>40</ItemKey></MultiSelect>
2 <MultiSelect><ItemKey>40</ItemKey><ItemKey>36</ItemKey></MultiSelect>
瞄准结果:
RowKey ItemKey
----------------
1 40
2 40
2 36
我已经接近我想要的下面的查询,但这只返回XML节点的NAME而不是其中的值:
SELECT
[RowKey],
x.y.value('local-name(.)', 'varchar(max)') AS ItemKey
FROM
[tbl_MyDataTable] AS t
cross apply t.[Format].nodes('MultiSelect/ItemKey') x(y)
结果:
RowKey ItemKey
----------------
1 ItemKey
2 ItemKey
2 ItemKey
任何建议都得到了很好的回复!
答案 0 :(得分:5)
你很接近 - 试试这个(因为这些都是INT
个数值,我建议你在XQuery中使用INT
:
SELECT
[RowKey],
x.y.value('(.)[1]', 'INT') AS ItemKey
FROM
dbo.[tbl_MyDataTable] AS t
CROSS APPLY
t.[Format].nodes('/MultiSelect/ItemKey') x(y)
基本上,选择(.)[1]
,您就会选择节点的值 - 而不是名称(即ItemKey
)< / p>