Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Creating multiple XML elements from related table

Status
Not open for further replies.

dande

Programmer
Feb 14, 2002
85
0
0
US
What syntax is required to have multiple elements generated to XML? Example 1 table of people relates to a table of phone numbers. The phone numbers table can have different types... home, cell, spouse...etc.

This is what I have MS SQL2008:
select
p1.id as '@id',
rtrim(p1.first) 'first',
rtrim(p1.last) 'last',
p2.id 'Phone/id',
rtrim(p2.phonetype) 'Phone/phonetype',
rtrim(p2.phonenumber)'Phone/phonenumber'
from person p1
left outer join phone p2 on p1.id = p2.personid
order by p1.last
for xml path('Person'),root ('People')

The output below has 2 of the same persons.. 1 for each related phone type.

How can I get phone element to repeat with the different related phone records?
<People>
<Person id="1">
<first>Tom</first>
<last>Wilson</last>
<Phone>
<id>1</id>
<phonetype>HOME</phonetype>
<phonenumber>(111)222-3333</phonenumber>
</Phone>
</Person>
<Person id="1">
<first>Tom</first>
<last>Wilson</last>
<Phone>
<id>2</id>
<phonetype>CELL</phonetype>
<phonenumber>(111)333-4444</phonenumber>
</Phone>
</Person>
</People>

Thanks in advance for any direction...
 
here is a quick attempt.

Code:
/*
DROP TABLE person 
DROP TABLE phone 
CREATE TABLE person (id int,[last] VARCHAR(50),[first] VARCHAR(50))
CREATE TABLE phone  (id int,personid INT,phonetype INT,phonenumber VARCHAR(50))

INSERT  INTO person VALUES  ( 1, 'ZZZ', 'AAA' )
INSERT  INTO person VALUES  ( 2, 'Bloggs', 'Joe' )

INSERT  INTO phone VALUES  ( 1, 1, 1, '000123' )
INSERT  INTO phone VALUES  ( 2, 1, 2, '000456' )
INSERT  INTO phone VALUES  ( 3, 1, 4, '000789' )
INSERT  INTO phone VALUES  ( 4, 2, 1, '000000' )
*/
SELECT  Person.id as 'PersonID',
        rtrim(person.[first]) 'First',
        rtrim(person.[last]) 'Last',
        Phone.id 'PhoneID',
        rtrim(Phone.phonetype) 'PhoneType',
        rtrim(Phone.phonenumber) 'PhoneNumber'
FROM    Person
        LEFT JOIN Phone ON Phone.personid = person.id
FOR     XML AUTO,
            ROOT('People'),
            ELEMENTS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top