Click here to Skip to main content
15,880,364 members
Articles / Database Development / SQL Server
Tip/Trick

Export data from SQL Server as XML

Rate me:
Please Sign up or sign in to vote.
4.46/5 (8 votes)
10 Aug 2011CPOL 115.2K   14   4
If you want to export data from a SQL Server in into XML, you can use the bulk copy utility (BCP) and FOR XML syntax. For example, lets say you want to export your internet sales by region from AdventureWorksDW as XML. Here is the query

SQL
SELECT 
	SalesRegion.SalesTerritoryRegion as Region,
	SUM(InternateSales.SalesAmount)  as SalesAmount
FROM dbo.FactInternetSales  InternateSales

LEFT JOIN dbo.DimSalesTerritory SalesRegion
ON InternateSales.SalesTerritoryKey = SalesRegion.SalesTerritoryKey

GROUP BY SalesRegion.SalesTerritoryRegion

FOR XML AUTO,TYPE, ELEMENTS ,ROOT('RegionSales')


This will give you result in XML in SSMS. If you want the result to be exported as separate XML document, put this query in BCP like this

BCP "SELECT 	SalesRegion.SalesTerritoryRegion as Region,	SUM(InternateSales.SalesAmount)  as SalesAmount FROM AdventureWorksDW2008.dbo.FactInternetSales  InternateSales LEFT JOIN AdventureWorksDW2008.dbo.DimSalesTerritory SalesRegion ON InternateSales.SalesTerritoryKey = SalesRegion.SalesTerritoryKey GROUP BY SalesRegion.SalesTerritoryRegion FOR XML AUTO,TYPE, ELEMENTS ,ROOT('RegionSales')" QUERYOUT "C:\SalesByRegion.XML" -c -t -T -S localhost


Replace the server name with you server name and location of XML to where you want it to be.

Read more about BCP here[^].
Read more about FOR XML clause here[^].

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United Kingdom United Kingdom
SQL Server developer and a geek

Comments and Discussions

 
QuestionWorked Perfectly! Pin
Member 81519518-Apr-14 8:01
Member 81519518-Apr-14 8:01 
GeneralMy vote of 5 Pin
awni22-Sep-13 0:49
awni22-Sep-13 0:49 
QuestionSQL to XML made simple - new open source tool available Pin
David Webber11-Oct-12 15:55
David Webber11-Oct-12 15:55 
GeneralReason for my vote of 4 Good one Pin
Shahriar Iqbal Chowdhury/Galib10-Aug-11 23:46
professionalShahriar Iqbal Chowdhury/Galib10-Aug-11 23:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.