Sql 使用多个同名元素解析OpenXML
我有这样的数据结构:Sql 使用多个同名元素解析OpenXML,sql,sql-server,sql-server-2008,openxml,sql-server-openxml,Sql,Sql Server,Sql Server 2008,Openxml,Sql Server Openxml,我有这样的数据结构: <rootnode> <group> <id>1</id> <anothernode>first string</anothernode> <anothernode>second string</anothernode> </group> <group> <id>2</id> &
<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>
这给了我结果
id | anothernode
————————————————
1 | first string
2 | third string
我怎样才能让它在所有四个字符串都显示的地方显示这个结果呢
id | anothernode
————————————————
1 | first string
1 | second string
2 | third string
2 | fourth string
或者可以使用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)
非常感谢你!你会建议其中一行多于另一行吗?嗯,这似乎输出了一行作为“1 | first string second string”我有没有办法在两个单独的行上获得“first string”和“second string”,这两个行都具有相同的ID?@billynomates,我建议你使用第二个版本(XML数据类型)。@billynomates查询对我来说很好。在这里测试它:
SELECT *
FROM OPENXML (@index, 'rootnode/group/anothernode')
WITH
(
id int '../id',
anothernode varchar(30) '.'
)
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)