当前位置: 代码迷 >> Sql Server >> 请教sql怎么遍历子节点的值
  详细解决方案

请教sql怎么遍历子节点的值

热度:1   发布时间:2016-04-24 10:18:15.0
请问sql如何遍历子节点的值?
declare @data xml,@txt varchar(max),@totalCount int,@count INT, @child XML
set @data='<root><id>a1</id><id>a2</id><id>a3</id><id>a4</id><id>a5</id><id>a6</id><id>a7</id><id>a8</id><id>a9</id><id>a10</id></root>'
SET @count=1;
SET @totalCount=@data.value('count(/root/id)','varchar');
While @count<=@totalCount 
BEGIN
 SET @child=@data.query('/root/id[position()=sql:variable("@count")]')
 set @txt= @child.value('(/id)[1]', 'nvarchar(max)')
     print @txt
 SET @count=@count+1
END


结果:
a1

若子节点条目少于10条,则结果会出现
a1
a2
a...
a9

当然是否有更加简单的方法遍历出
a1
a...
------解决方案--------------------

declare @data xml,@txt varchar(max),@totalCount int,@count INT, @child XML
set @data='<root>
<id>a1</id><id>a2</id><id>a3</id><id>a4</id>
<id>a5</id><id>a6</id><id>a7</id><id>a8</id>
<id>a9</id><id>a10</id></root>'
 
 
 SELECT tx1.x.query('.') item
,tx1.x.query('.').value('(/id)[1]','NVARCHAR(20)') item1
 FROM (
  SELECT @data d
 ) t
CROSS APPLY  t.d.nodes('/root/id') as tx1(x);

 
-- SET @totalCount=@data.value('count(/root/id)','varchar');  
-- 这里不应该是转为 int吗
  相关解决方案