Question

Hi I have XML data stored in a table. The XML Data looks something like this.

<Contacts>
  <Contact>
    <Name>Evan Gabriel</Name>
    <PhoneNumbers>
      <PhoneNumber Type="Home" Number="555-1224" />
      <PhoneNumber Type="Work" Number="578-9812" />
      <PhoneNumber Type="Cell" Number="578-7299" />
    </PhoneNumbers>
  </Contact>
  <Contact>
    <Name>Elizabeth Dallas</Name>
    <PhoneNumbers>
      <PhoneNumber Type="Home" Number="714-5488" />
      <PhoneNumber Type="Cell" Number="714-1099" />
    </PhoneNumbers>
  </Contact>
  <Contact>
    <Name>Anna Palmer</Name>
    <PhoneNumbers>
      <PhoneNumber Type="Work" Number="555-1440" />
      <PhoneNumber Type="Cell" Number="714-0523" />
    </PhoneNumbers>
  </Contact>
</Contacts>

What I am trying to do is to get The count of contact Numbers for each Client and I want the retuned output to be in XML datatype.

My Desired OUTPUT is as follows:

<Contacts>
  <Contact>
    <Name>Elizabeth Dallas</Name>
    <NumFound>2</NumFound>
  </Contact>
  <Contact>
    <Name>Anna Palmer</Name>
    <NumFound>2</NumFound>
  </Contact>
  <Contact>
    <Name>Evan Gabriel</Name>
    <NumFound>3</NumFound>
  </Contact>
</Contacts> 

Following is my attempt:

SELECT
    COUNT(*) AS NumCount
FROM
   (SELECT Xml_DATA FROM Xml_Table) AS XmlTable(XmlColumn)
CROSS APPLY 
   XmlColumn.nodes('/Contacts/Contact/Name/PhoneNumbers/PhoneNumber') XmlTableFunction(XmlColumn2)

But I dont think I am anywhere near the actual solution. Any help or pointer in the right direction is much appreciated.

Thank you in Advance.

SQL FIDDLE with Test Data and My Attempt

Était-ce utile?

La solution

Try this:

declare @Contacts xml = '<Contacts>
  <Contact>
    <Name>Evan Gabriel</Name>
    <PhoneNumbers>
      <PhoneNumber Type="Home" Number="555-1224" />
      <PhoneNumber Type="Work" Number="578-9812" />
      <PhoneNumber Type="Cell" Number="578-7299" />
    </PhoneNumbers>
  </Contact>
  <Contact>
    <Name>Elizabeth Dallas</Name>
    <PhoneNumbers>
      <PhoneNumber Type="Home" Number="714-5488" />
      <PhoneNumber Type="Cell" Number="714-1099" />
    </PhoneNumbers>
  </Contact>
  <Contact>
    <Name>Anna Palmer</Name>
    <PhoneNumbers>
      <PhoneNumber Type="Work" Number="555-1440" />
      <PhoneNumber Type="Cell" Number="714-0523" />
    </PhoneNumbers>
  </Contact>
</Contacts>'

select 
    c.query('*[local-name()!="PhoneNumbers"]'),
    NumFound = c.value('count(.//PhoneNumber)', 'int')
from @Contacts.nodes('//Contact') c(c)
for xml path('Contact'), root('Contacts')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top