Sunday, June 27, 2021

Query to generate Single XML from multiple tables in SQL Server

Here is the sample code to generate a single xml from multiple table query in Sql Server. In this example I am querying data from two tables.

Sample Query :
  1. SELECT
  2. (SELECT * FROM dbo.TableA FOR XML PATH('TableA'), TYPE),
  3. (SELECT * FROM dbo.TableB FOR XML PATH('TableB'), TYPE)
  4. FOR XML PATH(''), ROOT('root')

XML Output :
  1. <root>
  2. <TableA>
  3. <Column1>Value1</Column1>
  4. <Column2>Value2</Column2>
  5. </TableA>
  6. <TableB>
  7. <Column1>Value1</Column1>
  8. <Column2>Value2</Column2>
  9. </TableB>
  10. </root>

You can load this Xml into DataSet using below C# code.
  1. DataSet ds = new DataSet();
  2. ds.ReadXml("queryResult.xml");

No comments:

Post a Comment