I have the following table structure:
Customers:
CustomerId Name City
1 Richie Rich MyCity
2 Bernie Bertel MyTown
Contacts:
ContactId CustomerId Name Telephone
1 1 Test 123123
I want to get the result in an XML Structure like the following:
<Customers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Customers>
<Name>Richie Rich</Name>
<City>MyCity</City>
<Contacts>
<Contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Name>Test</Name>
<Telephone>123123</Telephone>
</Contact>
</Contacts>
</Customers>
<Customers>
<Name>Bernie Bertel</Name>
<City>MyTown</City>
<Contacts xsi:nil="true" />
</Customers>
</Customers>
The corresponding T-SQL Query is:
SELECT
Name,
City,
(
SELECT
Name,
Telephone
FROM Contacts
WHERE (Customers.CustomerId = Contacts.CustomerId)
FOR XML PATH ('Contact'), TYPE, ELEMENTS XSINIL
) AS Contacts
FROM Customers
FOR XML AUTO, ROOT('Customers'), TYPE, ELEMENTS XSINIL
For the further processing, I must know the structure of the list-nodes (Contact). So if the Customers have no Contacts (like in the second entry), I must know which fields/columns the Customer node has.
Does anyone know how to resolve this?