We help IT Professionals succeed at work.
Get Started

SQL Server XML Select sub tables

Larry Brister
on
200 Views
Last Modified: 2018-03-21
In my following code I am getting ONLY the top phone number for the individuals from the Phone.*

This...
SELECT TOP 10
        Employee.IndividualID ,
        Employee.FirstName ,
        Employee.LastName,
        Phone.*
FROM    Individuals AS Employee
        INNER JOIN ( SELECT IndividualID AS IndividualID,
                            Code AS CODE,
                            [Description] AS [DESCRIPTION] ,
                            PhoneNumber AS PhoneNumber
                     FROM   dbo.vwIndividualPhones        
                   ) Phone ON Phone.IndividualID = Employee.IndividualID
FOR     XML AUTO , ROOT('Employees') , ELEMENTS; 

Open in new window


Gets me this...
<Employees>
  <Employee>
    <IndividualID>1747652</IndividualID>
    <FirstName>ALICIA</FirstName>
    <LastName>SMITH</LastName>
    <Phone>
      <IndividualID>1747652</IndividualID>
      <CODE>HP</CODE>
      <DESCRIPTION>Home Phone</DESCRIPTION>
      <PhoneNumber>1111111111</PhoneNumber>
    </Phone>
  </Employee>
</Employees>

Open in new window


When I want this...

<Employees>
  <Employee>
    <IndividualID>1747652</IndividualID>
    <FirstName>ALICIA</FirstName>
    <LastName>SMITH</LastName>
<Phones>
    <Phone>
      <IndividualID>1747652</IndividualID>
      <CODE>HP</CODE>
      <DESCRIPTION>Home Phone</DESCRIPTION>
      <PhoneNumber>1111111111</PhoneNumber>
    </Phone>
    <Phone>
      <IndividualID>1747652</IndividualID>
      <CODE>WP</CODE>
      <DESCRIPTION>Work Phone</DESCRIPTION>
      <PhoneNumber>2222222222</PhoneNumber>
    </Phone>
</Phones>
  </Employee>
</EMployees>

Open in new window

Comment
Watch Question
Senior Manager
CERTIFIED EXPERT
Commented:
This problem has been solved!
Unlock 1 Answer and 4 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE