简体   繁体   中英

SQL querying XML attributes

I have an XML that I'm trying to query with SQL.

  <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. 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. This unsurprising does not pick up both nodes from 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.

Name should still use tc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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