Search code examples
sqlsql-serverxmlsql-server-2008-r2sqlxml

SQL Select XML nodes, parametrize node number


I'm selecting data from a XML document, however I need to loop through each child node perform some actions on them.

At present I have a while exists loop around the select but don't know how to parametrize the node number.

I understand the below isn't right but would appreciate it if someone could point out the best way to parametrize the node selection.

Thanks.

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

The XML is as follows:

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

Solution

  • you can get all data by one query with nodes() function:

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

    sql fiddle demo

    Or, if you really want to loop, you can use sql:variable() extension function:

    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