使用SQL查询读取XML子节点属性

时间:2013-07-31 13:40:06

标签: sql sql-server xml xml-attribute

我在表(Qualifications)中有一个XML列(Criteria),它包含不同的XML:

<training ID="173"><badge ID="10027" /><badge ID="10028" /></training>
<book Category="Hobbies And Interests" PropertyName="C#" CategoryID="44" />
<sport Category="Hobbies And Interests" PropertyName="Cricket" CategoryID="46" />
<education ID="450" School="Jai ambe vidyalaya"></education>

我想阅读“training”节点下所有节点的“badge”节点“ID”属性。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:6)

badge内的training个元素的ID

select t.c.value('.', 'int') ID
from Qualifications q
    cross apply q.Criteria.nodes('//training[badge]/badge[@ID]/@ID') t(c)

badge个元素的ID(不仅在training内)

select t.c.value('.', 'int') ID
from Qualifications q
    cross apply q.Criteria.nodes('//badge[@ID]/@ID') t(c)

如果Criteria列为nvarchar类型,您可以转换为xml

select t.c.value('.', 'int') ID
from Qualifications q
    cross apply (select convert(xml, q.Criteria) xmlCriteria) a
    cross apply a.xmlCriteria.nodes('//training[badge]/badge[@ID]/@ID') t(c)

答案 1 :(得分:6)

试试这个样本,它应该有帮助(只需用你的表/列名替换@xml)

DECLARE @xml XML
SET @xml ='
<training ID="173">
    <badge ID="10027" />
    <badge ID="10028" />
</training>
<book Category="Hobbies And Interests" PropertyName="C#" CategoryID="44" />
<sport Category="Hobbies And Interests" PropertyName="Cricket" CategoryID="46" />
<education ID="450" School="Jai ambe vidyalaya"></education>'

SELECT data.col.value('(@ID)[1]', 'int')
FROM @xml.nodes('(/training/badge)') AS data(col)

输出:

10027
10028