Prøv noget som dette - det bruger FOR XML PATH
og undervælger at oprette de "linkede" undernoder for en given kunde (Jeg begrænsede dette til to undertabeller - men du burde få "kernen" af det og være i stand til at udvide det til et hvilket som helst antal sammenkædede undertabeller ):
SELECT
CustomerID AS '@CustomerID',
CustName AS '@Name',
(SELECT ProductName AS '@productname'
FROM dbo.Products p
WHERE p.CustomerID = c.CustomerID
FOR XML PATH('Product'), TYPE) AS 'Products',
(SELECT HobbyName AS '@hobbyname'
FROM dbo.Hobbies h
WHERE h.CUstomerID = c.CustomerID
FOR XML PATH('Hobby'), TYPE) AS 'Hobbies'
FROM
dbo.Customers c
FOR XML PATH('Customer'), ROOT('Customers')
Giver mig et output som ligner:
<Customers>
<Customer CustomerID="1" Name="Fred">
<Products>
<Product productname="Table" />
<Product productname="Wardrobe" />
<Product productname="Chair" />
</Products>
<Hobbies>
<Hobby hobbyname="Golf" />
<Hobby hobbyname="Swimming" />
</Hobbies>
</Customer>
<Customer CustomerID="2" Name="Sue">
<Products>
<Product productname="CD Player" />
<Product productname="Picture frame" />
</Products>
<Hobbies>
<Hobby hobbyname="Dancing" />
<Hobby hobbyname="Gardening" />
<Hobby hobbyname="Reading" />
</Hobbies>
</Customer>
</Customers>