Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save SQL query result to XML file on disk

I would like to export table from SQL Server 2012 to XML file. I have found nice answer and here how to make XML result from SQL Server database query, but still I am missing how to save this result physically into file.

SQL query is:

SELECT [Created], [Text]
FROM [db304].[dbo].[SearchHistory]
FOR XML PATH('Record'), ROOT('SearchHistory')

I use Microsoft SQL Server Management Studio to execute this result. I see the XML in a result window, but I cannot save it.

There is "Save Result As.." in context menu, but with 98900 rows I run out of my 8GB memory with this option.

Is there a way how to save this query directly to the XML file on disk?

like image 478
Tomas Kubes Avatar asked Aug 06 '16 20:08

Tomas Kubes


People also ask

How do I save the results of SQL query in a file?

Click Query, and then click Results to File. Enter and then execute the SQL statement. In the Save Results dialog box, specify the following settings: Save In: Select a directory in which to save the file.


2 Answers

You can also your SQL Server's extended stored procedures to export it to an xml file.

But you would need to configure the sql server before you can use it.

EXEC master.dbo.sp_configure 'show advanced options', 1
RECONFIGURE
EXEC master.dbo.sp_configure 'xp_cmdshell', 1
RECONFIGURE

Once xp_cmdshel is enabled in the SQL Server. You can use the following command to export the data to an xml file.

EXEC xp_cmdshell 'bcp "SELECT [Created], [Text] FROM [db304].[dbo].[SearchHistory] FOR XML PATH(''Record''), ROOT(''SearchHistory'')" queryout "C:\bcptest.xml" -T -c -t,'
like image 144
M.Ali Avatar answered Sep 18 '22 09:09

M.Ali


You can always use the "Results to File" option in SSMS:

enter image description here

That should output the results of the query execution directly into a file on disk

like image 26
marc_s Avatar answered Sep 21 '22 09:09

marc_s