I'm using SELECT ... FOR XML to generate XML and it creates exactly what I want to see - in SSMS. But...
The problem I have is, the exported XML file has the entire XML body on a single line. It's valid XML, but how can I format the output? (one element per line, terminated with \r\n and preferably indented) The file should be human readable in notepad.
Also, is there a better way to tack on the XML header?
Of course I could write a CLR stored proc to do the export, seems like overkill though. (Why is this even hard?)
ALTER PROCEDURE [dbo].[ExportConfigTablesToXML]
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
--EXEC sp_configure 'show advanced options', 1
--RECONFIGURE
--EXEC sp_configure 'xp_cmdshell', 1
--RECONFIGURE
--EXEC sp_configure 'show advanced options', 0
--RECONFIGURE
DECLARE @FileName VARCHAR(50)
DECLARE @SQLCmd VARCHAR(500)
DECLARE @CreateXmlHeader varchar(500)
DECLARE @AppendXmlBody varchar(500)
DECLARE @DeleteTempFile varchar(500)
SELECT @FileName = 'C:\Temp\SampleXMLOutput.xml'
SELECT @SQLCmd = 'bcp ' +
'"SELECT Name AS [@Name], ServiceName, MachineName,' +
' CASE PollInterval WHEN 10 THEN NULL ELSE PollInterval END AS PollInterval,' +
' CASE Alerts WHEN 1 THEN NULL ELSE ''false'' END AS Alerts, ' +
' CASE Pages WHEN 1 THEN NULL ELSE ''false'' END AS Pages' +
' FROM Watchdog.dbo.[Config.Services] [Service]' +
' FOR XML PATH(''Service''), ROOT(''Services'')"' +
' queryout ' +
@FileName + '.tmp' +
' -S' + @@SERVERNAME +
' -T -c -r -t'
SET @CreateXmlHeader = 'ECHO ^<?xml version="1.0" ?^> > ' + @FileName
SET @AppendXmlBody = 'TYPE ' + @FileName + '.tmp >> ' + @FileName
SET @DeleteTempFile = 'DEL ' + @FileName + '.tmp'
EXECUTE master..xp_cmdshell @SQLCmd
EXECUTE master..xp_cmdshell @CreateXmlHeader
EXECUTE master..xp_cmdshell @AppendXmlBody
EXECUTE master..xp_cmdshell @DeleteTempFile
END