Home Forums Programming XML Nesting SQL to XML Grouping issue RE: Nesting SQL to XML Grouping issue

  • Hi, the reason why the xml is changing when you add the additional predicate is because the sub query is only returning a single record (item) for each account rather than a batch of items per acct. You can see this easier by commenting out the outer for xml clause and see what is returned.

    it may be me, but I didn't really get how you needed the query to function exactly so I've had to make some assumptions to the intentions of your query and the actual structure you need the xml to look like.

    I've come up with the below (converting your query to use sys.tables/sys.columns to mimic acct/item) which I think may get you closer to a better xml structure:

    SELECT

    AC.name AS 'Acct',

    (SELECT column_id AS 'data()'

    FROM sys.columns AS ITEMS1

    WHERE ITEMS1.object_id = AC.object_id

    FOR XML PATH ('Item'), ROOT('Items'), TYPE)

    FROM

    sys.tables AC WITH(NOLOCK)

    FOR XML PATH ('Account'), ROOT ('Accts'), ELEMENTS

    hope this helps.. if not, then if you can describe how you need the final xml to look like then that will help with an answer.