Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert records in a table to xml format using T-SQL?

I've got a simple table and want to store its content into a xml on the harddrive. There should be one root element for the whole table, one element per table row and one child element per table column.

What possibilities do I have?

Thanks a lot Tomas

like image 495
Tomas Walek Avatar asked Oct 14 '09 06:10

Tomas Walek


People also ask

How do I export data from SQL table to XML?

If you want to export the whole SQL Server database to the XML file, you can first use the SQL Server Management Studio to export your SQL database to CSV, and then convert CSV to XML using an online converter. You ca also choose to output SQL Server database to Excel and then convert Excel (XLS) to XML.

How can I get SQL query results in XML?

You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.


2 Answers

And if you need more control over how the resulting XML looks like, check out the new FOR XML PATH statement in SQL Server 2005 and newer.

A statement like this (based on the infamous Northwind database):

SELECT 
   CustomerID as "@CustomerID",
   CompanyName,
   Address as "address/street",
   City as "address/city",
   Region as "address/region",
   PostalCode as "address/zip",
   Country as "address/country",
   ContactName as "contact/name",
   ContactTitle as "contact/title",
   Phone as "contact/phone", 
   Fax as "contact/fax"
FROM Customers
FOR XML PATH('Customer')

will result in an output like this:

  <Customer CustomerID="ALFKI">
    <CompanyName>Alfreds Futterkiste</CompanyName>
    <address>
      <street>Obere Str. 57</street>
      <city>Berlin</city>
      <zip>12209</zip>
      <country>Germany</country>
    </address>
    <contact>
      <name>Maria Anders</name>
      <title>Sales Representative</title>
      <phone>030-0074321</phone>
      <fax>030-0076545</fax>
    </contact>
  </Customer>

That's rather tricky to get any other way....

Marc

like image 196
marc_s Avatar answered Oct 04 '22 06:10

marc_s


Use the FOR XML in your query.

E.g: select * from table1 FOR XML AUTO

see this --> http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1265579,00.html

Alternatively, you can create your own XML in your t-sql code through cursors or in your application code, the longer way of doing it.

like image 29
Bhaskar Avatar answered Oct 04 '22 05:10

Bhaskar