2011-11-04 122 views
4

我有一個數據結構,例如:解析處理OpenXML具有相同名稱的多個元素

<rootnode> 
    <group> 
    <id>1</id> 
    <anothernode>first string</anothernode> 
    <anothernode>second string</anothernode> 
    </group> 
<group> 
    <id>2</id> 
    <anothernode>third string</anothernode> 
    <anothernode>fourth string</anothernode> 
    </group> 
</rootnode> 

和以下的代碼:

EXEC sp_xml_preparedocument @index OUTPUT, @XMLdoc 

SELECT * 
FROM OPENXML (@index, 'rootnode/group') 
WITH 
(
    id int 'id', 
    anothernode varchar(30) 'anothernode' 
) 

這使我的結果

id | anothernode 
———————————————— 
1 | first string 
2 | third string 

我怎樣才能讓它顯示這個結果,而不是所有四個字符串都顯示?

id | anothernode 
———————————————— 
1 | first string 
1 | second string 
2 | third string 
2 | fourth string 

回答

9
SELECT * 
FROM OPENXML (@index, 'rootnode/group/anothernode') 
WITH 
(
    id int '../id', 
    anothernode varchar(30) '.' 
) 

或者你也可以使用XML數據類型,而不是像這樣:

SELECT G.N.value('(id/text())[1]', 'int') AS id, 
     A.N.value('text()[1]', 'varchar(30)') AS anothernode 
FROM @XMLDoc.nodes('rootnode/group') AS G(N) 
    CROSS APPLY G.N.nodes('anothernode') AS A(N) 
+0

非常感謝您!你會建議哪一個比另一個更多? –

+0

嗯,這似乎輸出一行爲「1 |第一個字符串第二個字符串」有什麼辦法我可以得到「第一個字符串」和「第二個字符串」在兩個單獨的行上都有相同的ID? –

+0

@billynomates,我建議你使用第二個版本(XML數據類型)。 –

相關問題