2010-09-13 76 views
0

我有下面的XMLTSQL XML(可使用XQuery)

<myroot> 
<scene> 
<sceneId>983247</sceneId> 
<item> 
<coordinates> 
<coordinate>0</coordinate> 
<coordinate>1</coordinate> 
<coordinate>2</coordinate> 
<coordinate>3</coordinate> 
</coordinates> 
<Values> 
<Value>34</Value> 
<Value>541</Value> 
<Value>255</Value> 
<Value>332</Value> 
</Values> 
</item> 
</scene> 
</myroot> 

我该如何使用TSQL以下结果:

Col1 Col2 
0 34  
1 541 
2 255 
3 332 

感谢,

中号

+0

XML文档存储在哪里? – annakata 2010-09-13 15:50:27

回答

1

此XPath 2.0表达式:

/myroot/scene/item/ 
    string-join(for $pos in (0 to max(*/count(*))) 
       return string-join(for $col in (1 to max(count(*))) 
            return if ($pos=0) 
             then concat('Col',$col) 
             else *[$col]/*[$pos], 
            ' '), 
       '&#xA;') 

输出:

Col1 Col2 
0 34 
1 541 
2 255 
3 332 
+1

试图像这样运行: 选择@ xml.query(” /myroot /场景/项目/ 字符串连接(为$ POS在(0至最大(*/COUNT(*))) 返回字符串-join($ col in(1 to max(count(*))) return if($ pos = 0) then concat('Col',$ col) else * [$ col]/* [$ pos ], ''), ' ')') 似乎不起作用 – koumides 2010-09-13 16:49:28

+0

@koumides:'fn:count()'必须有一个参数。第一个'fn:max'调用将元素的最大数目计入某个“列”。所以它必须是'max(*/count(*))'。 – 2010-09-13 16:59:53

0

这里是我的XML小白的做法。本身是一个序列

如果你只信任元素排序,而不是坐标值:

select 
    coordinate = max(case when element = 'coordinate' then elemval end) 
, value  = max(case when element = 'Value' then elemval end) 
from (
    select 
    element = row.value('local-name(.)','varchar(32)') 
    , elemval = row.value('.','int') 
    , position = row.value('for $s in . return count(../*[. << $s]) + 1', 'int') 
    from @xml.nodes('/myroot/scene/item/*/*') a (row) 
) a 
group by position 

或者写成两个.nodes()JOIN(你的想法)。

如果你信任的坐标编号是从零开始的顺序:如果你只相信坐标编号是一个序列,但

select 
    coordinate = row.value('for $s in . return count(../*[. << $s]) + 1', 'int') 
      - 1 
, value  = row.value('.','int') 
from @xml.nodes('/myroot/scene/item/Values/*') a (row) 

从任意种子:

select 
    coordinate = row.value('for $s in . return count(../*[. << $s]) + 1', 'int') 
      + row.value('(/myroot/scene/item/coordinates/coordinate)[1]','int') 
      - 1 
, value  = row.value('.','int') 
from @xml.nodes('/myroot/scene/item/Values/*') a (row) 

路径可以缩写:

  • /myroot/scene/item/*/* - >//item/*/*
  • /myroot/scene/item/Values/* - >//Values/*
  • /myroot/scene/item/coordinates/coordinate - >//coordinate

但我不知道这两种方式的智慧。

//item/*/*可能可以做得更具体,所以它只包括coordinateValue边缘节点,但我不知道语法。