2010-09-13 81 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邊緣節點,但我不知道語法。