views:

316

answers:

1

I am working on retrieving data in Xml format from SQL Server 05 using FOR XML

What is the best practice for nesting elements in my resulting Xml?

Currently I am doing this:

Select 
    (
        Select 
            [Col1] As [Col1],
            [Col2] As [Col2]
        From [dbo].[NestedTable] As T1
        Where T0.[Key] = T1.[Key]
        FOR XML PATH('NestedTable'), TYPE   
    ),
    [Col1] As [Col1],
    [Col2] As [Col2],
From [dbo].[TopLevelTable] As T0
FOR XML PATH('TopLevelTable'), ROOT('TopLevelTableItems')   

However, I am concerned about the performance of this due to the correlated sub query. Is there Group By type functionality that I can use so that I can do a regular inner join on the two tables and have resulting Xml where the top level nodes are unique and have the appropriate collection of child nodes?

Cheers

-Leigh

A: 

Correlated sub-queries should be avoided if possible (not a big deal if the tables are guaranteed to be small).

Perhaps you should first define the XML schema (presumably something is consuming this and expects a certain format).

Mitch Wheat
Hey Mitch, Yeh I have a well defined XSD that I am validating against before using the XML. The issue I've got is getting a nested XML structure without using a correlated subquery. Am I missing something regarding using XML schemas to generate my XML from SQL?
Leigh Shayler