I am trying to convert a query to return as xml in the correct format
The query is simply SELECT * FROM [TABLENAME]
, and yes it has to be *
as this is used for a dynamic utility that needs to work on any table.
Anyhow, I want the resulting records to be nested two levels deep like this
<Root>
<RecordParent>
<Record>
<!--Fields selected with * end up here-->
</Record>
</RecordParent>
<RecordParent>
<Record>
<!--Fields selected with * end up here-->
</Record>
</RecordParent>
<RecordParent>
<Record>
<!--Fields selected with * end up here-->
</Record>
</RecordParent>
</Root>
But I can't seem to get this xml, the best I've done is
SELECT (
SELECT * FROM tableName FOR XML PATH('Record'), TYPE
) FOR XML PATH('RecordParent'), ROOT('Root')
Which ends up like
<Root>
<RecordParent>
<Record>
<!--Fields selected with * end up here-->
</Record>
<Record>
<!--Fields selected with * end up here-->
</Record>
<Record>
<!--Fields selected with * end up here-->
</Record>
</RecordParent>
</Root>
Any ideas how I can get the correct result with FOR XML
?
EDIT
I can do it in a few lines
DECLARE @xml xml
SET @xml = (SELECT TOP 10 * FROM tableName FOR XML PATH('Record'), ROOT('Records'))
SELECT r.query('.')FROM @xml.nodes('//Record') R(r) FOR XML PATH('RecordParent'), ROOT('Root'), TYPE