问题
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?
回答1:
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,'
回答2:
You can always use the "Results to File" option in SSMS:
That should output the results of the query execution directly into a file on disk
回答3:
To this job in SQL Server 2012 is a pain in ass. Finally I end up to update it to SQL Server 2014 as there is already support for SQL UTF-8 files in sqlcmd.
- Create an SQL query and save it to the file.
run following:
sqlcmd -S -U sa -P sapassword -i inputquery_file_name -C65001 -o outputfile_name
来源:https://stackoverflow.com/questions/38808516/how-to-save-sql-query-result-to-xml-file-on-disk