SQL Select XML nodes, parametrize node number

本小妞迷上赌 提交于 2019-12-11 09:48:47

问题


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>

回答1:


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



来源:https://stackoverflow.com/questions/19158537/sql-select-xml-nodes-parametrize-node-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!