简体   繁体   English

SQL查询XML属性

[英]SQL querying XML attributes

I have an XML that I'm trying to query with 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>

Notice that InvestmentD has both a Dividend and Cap account type. 请注意,InvestmentD具有股息和上限帐户类型。 So I tried to query this data with the following: 因此,我尝试使用以下查询此数据:

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)

where @x is the XML. 其中@x是XML。 This unsurprising does not pick up both nodes from InvestmentD. 这种毫不奇怪的是,不会从InvestmentD获得两个节点。 I can't figure out how to parse all the nodes. 我不知道如何解析所有节点。 A pointer in the right direction would be appreciated. 朝着正确方向的指针将不胜感激。 Thanks. 谢谢。

Add a cross apply tcnodes('Account') as a(c) and fetch the attribute values from ac without specifying Acount in the xPath expression. 添加cross apply tcnodes('Account') as a(c)并从ac获取属性值,而无需在xPath表达式中指定Acount

Name should still use tc . 名称仍应使用tc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM