I am trying to return XML using FOR XML
from a SQL query, and I'm almost there, except it seems like I can't get it to the exact format I need it.
Here is the statement I constructed so far:
SELECT TOP 1
ID AS '@id'
,1 AS '@version'
,'en' AS '@lang'
,'Joe Smith' AS 'field/Name'
,'[email protected]' AS 'field/Email'
FROM Table
FOR XML PATH ('add')
The XML format it returns:
<add id="123" version="1" lang="en">
<field>
<Name>Joe Smith</Name>
<Email>[email protected]</Email>
</field>
</add>
How I need it to return:
<add id="123" version="1" lang="en">
<field name="Name">Joe Smith</field>
<field name="Email">[email protected]</field>
</add>
How do I do this, so far that's the furthest I got with the documentation I found online.. Please help.
1)
2) Second solution uses a template and variables. I propose this solution because i saw
TOP 1
(maximum one row). First you should transfer the values from that row into variables (SELECT @Variable = Column, ... FROM Table
). You have greater flexibility but the performance could be affected (note: I didn't do any tests).