You are on page 1of 3

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

Ask Question

20

6
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
sql-server xml tsql
share
improve this question
edited Oct 14 '09 at 6:56

marc_s
576k12911111258
asked Oct 14 '09 at 6:19

Tomas Walek
1,61321734
add a comment
3 Answers
active
oldest
votes

30

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.

share
improve this answer
edited Nov 21 '13 at 21:36

Preet Sangha
54.6k15113184
answered Oct 14 '09 at 6:22

Bhaskar
6,95663957

Thank you, Bhaskardeep Khaund! That solved my issue. � Tomas Walek Oct 14 '09 at
6:51
1
The link in this answer requires membership to view. � Gibron Jul 26 '12 at 21:44
add a comment

46
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

share
improve this answer
edited Jun 14 '12 at 2:27

scw
2,79262142
answered Oct 14 '09 at 6:56

marc_s
576k12911111258

How do I do the reverse i.e. convert XML back to a table � Raihan Iqbal Dec 14 '17
at 4:57
1
@RaihanIqbal: look at the built-in XQuery support in T-SQL - using .query(),
.nodes() and .value(), you can definitely do that - but that's a whole different
question :-) � marc_s Dec 14 '17 at 5:37
2
This is good stuff! I'd only add that the Questioner wanted "one root element for
the whole table". To do this, simply add ROOT('Root') like so: FOR XML
PATH('Customer'), ROOT('Customers') � MikeTeeVee Jun 30 '18 at 21:37
add a comment
0

SELECT CAST('1' AS XML)


This Query fire in sql and your copy data put inside then show XML Result.

share
improve this answer
edited May 9 '18 at 7:31

answered May 9 '18 at 7:26

You might also like