0

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.

4

1 回答 1

0

Add a cross apply t.c.nodes('Account') as a(c) and fetch the attribute values from a.c without specifying Acount in the xPath expression.

Name should still use t.c.

于 2013-01-15T21:05:22.600 回答