2013-07-31 68 views
4

我有表(資格)一個XML列(標準),其中包含不同的XML:爲讀取XML子節點屬性使用SQL查詢

<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」屬性「訓練」節點下的所有節點。

任何人都可以幫忙嗎?的badge元素的任何地方badge元素中training只有

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

的ID(不僅內部training

回答

6

標識

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

如果Criterianvarchar類型,可以轉換爲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) 
+0

謝謝您的時間和幫助! –

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 
+0

謝謝你的時間和幫助! –

+0

It works Great John ... thanks .. :) –