SQL选择XML节点,参数化节点编号

时间:2013-10-03 11:53:40

标签: sql sql-server xml sql-server-2008-r2 sqlxml

我正在从XML文档中选择数据,但是我需要遍历每个子节点对它们执行一些操作。

目前我在select周围有一个while循环,但不知道如何参数化节点号。

我理解下面的内容不对,但如果有人能指出参数化节点选择的最佳方法,我将不胜感激。

感谢。

DECLARE @nodeCount varchar(1) = '1'
WHILE EXISTS (SELECT table.value('(Info/Data/DataInfo/Type/node())[' + @nodeCount + ']', 'nvarchar(10)') from table)

XML如下:

<Info xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Data>
<DataInfo>
  <Description>11111111111</Description>     
  <Type>1</Type>
</DataInfo>
<DataInfo>
  <Description>2222222222222</Description>     
  <Type>2</Type>
</DataInfo>
<DataInfo>
  <Description>3333333333333</Description>    
  <Type>3</Type>
</DataInfo>
</Data>
</Info>

1 个答案:

答案 0 :(得分:2)

您可以使用nodes()函数通过一个查询获取所有数据:

select
    t.c.value('(text())[1]', 'nvarchar(10)') as [Type]
from @xml.nodes('/Info/Data/DataInfo/Type') as t(c)

<强> sql fiddle demo

或者,如果您真的想要循环,可以使用sql:variable()扩展功能:

DECLARE @nodeCount int = 1
WHILE EXISTS (SELECT table.value('(Info/Data/DataInfo/Type/node())[sql:variable("@nodeCount")][1]', 'nvarchar(10)') from table)

<强> sql fiddle demo