2013-01-15 72 views
0

我有一個XML,我試圖用SQL查詢。SQL查詢XML屬性

<QueryB> 
     <investment name="InvestmentA"> 
     <Account Type="DIVIDEND"> 
      <glsum YTD="0.0000" /> 
      <glsum Inception="111111.0000" /> 
      <glsum QTD="0.0000" /> 
     </Account> 
     </investment> 
     <investment name="InvestmentB"> 
     <Account Type="DIVIDEND"> 
      <glsum YTD="0.0000" /> 
      <glsum Inception="222222.0000" /> 
      <glsum QTD="0.0000" /> 
     </Account> 
     </investment> 
     <investment name="InvestmentC"> 
     <Account Type="CAP"> 
      <glsum YTD="90.0000" /> 
      <glsum Inception="333333.0800" /> 
      <glsum QTD="90.0000" /> 
     </Account> 
     </investment> 
     <investment name="InvestmentD"> 
     <Account Type="CAP"> 
      <glsum YTD="0.0000" /> 
      <glsum Inception="555555.0000" /> 
      <glsum QTD="0.0000" /> 
     </Account> 
     <Account Type="DIVIDEND"> 
      <glsum YTD="0.0000" /> 
      <glsum Inception="444444.0000" /> 
      <glsum QTD="0.0000" /> 
     </Account> 
     </investment> 

請注意,InvestmentD同時具有股息和上限賬戶類型。所以,我想用下面的查詢這個數據:

select rtrim(ltrim(t.c.value('@name', 'nvarchar(500)'))) as name, 
    rtrim(ltrim(t.c.value('(Account/@Type)[1]', 'nvarchar(500)'))) as Type, 
    rtrim(ltrim(t.c.value('(Account/glsum/@YTD)[1]', 'nvarchar(500)'))) as YTD, 
    rtrim(ltrim(t.c.value('(Account/glsum/@Inception)[1]', 'nvarchar(500)'))) as inception, 
    rtrim(ltrim(t.c.value('(Account/glsum/@QTD)[1]', 'nvarchar(500)'))) as QTD 
from @x.nodes('/QueryB/investment')t(c) 

其中@x是XML。這一點並不令人驚訝,並沒有從InvestmentD中獲取兩個節點。我無法弄清楚如何解析所有的節點。一個指針在正確的方向將不勝感激。謝謝。

回答

0

添加一個cross apply t.c.nodes('Account') as a(c)並從a.c中獲取屬性值,而無需在xPath表達式中指定Acount

名稱仍應使用t.c

+0

太棒了。謝謝。 –