Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Root element with FOR XML

Status
Not open for further replies.

theoxyde

Programmer
Jul 16, 2003
220
US
Is there any way to get a root element into a FOR XML AUTO query?

For example:
Code:
select * from tableA
join tableB on tableA.id = tableB.idA
for xml auto
Each record for tableB is nested properly within the tableA result, but there is no root node above tableA's results.

I've seen examples using SQL Server over IIS, but that isn't an option in this case.
 
If using "FOR XML AUTO, ELEMENTS" does not get you what you want, then you will probably have to use "FOR XML EXPLICIT". You would then have to re-write your query using UNION. Here is an example:
Code:
SELECT     1 As Tag, 
        NULL As Parent, 		
 [tableA.id] As [MyRoot!1!MyId!element]
        NULL As [MyID!2!MyField]
FROM tableA

UNION

SELECT     2, 
           1,
 [tableA.id]
 [tableB.MyField]

FROM tableA
JOIN tableB
ON tableA.id = tableB.idA
ORDER BY [MyRoot!1!MyId!element]

FOR XML EXPLICIT
Good Luck!
 
AUTO and AUTO, ELEMENTS is fine if there is only one result being returned. I'll look into the EXPLICIT though.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top