2013-01-15 71 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

太棒了。谢谢。 –