4

我在表(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>

我想读取“训练”节点下所有节点的“徽章”节点“ID”属性。

任何人都可以帮忙吗?

4

2 回答 2

6

badge内部元素的 IDtraining

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

任何地方的元素 ID badge(不仅是 inside training

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

如果Criteriacolumn 是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)
于 2013-07-31T13:43:27.170 回答
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
于 2013-07-31T13:52:51.243 回答