Click here to Skip to main content
Click here to Skip to main content

Export data from SQL Server as XML

By , 10 Aug 2011
 
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
 
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)

About the Author

seankk
Software Developer
United Kingdom United Kingdom
Member
SQL Server developer and a geek

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSQL to XML made simple - new open source tool availablememberDavid Webber11 Oct '12 - 15:55 
Check out this video to see how (http://www.youtube.com/user/TheCAMeditor) to do all this code-free using the CAM editor toolset.
 
Connect via JDBC to your SQL tables - then simply visually drag and drop to build the XML you need.
 
Run the engine - generate your XML.
 
Download the open source tool from the CAM Editor project site - http://www.cameditor.org
 
Enjoy.
GeneralReason for my vote of 4 Good onememberShahriar Iqbal Chowdhury10 Aug '11 - 23:46 
Reason for my vote of 4
Good one

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 10 Aug 2011
Article Copyright 2011 by seankk
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid