Note that there are some explanatory texts on larger screens.

plurals
  1. POT-SQL: exporting table to XML using stored proc - how to format?
    primarykey
    data
    text
    <p>I'm using SELECT ... FOR XML to generate XML and it creates exactly what I want to see - <em>in SSMS</em>. But...</p> <p>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.</p> <p>Also, is there a better way to tack on the XML header?</p> <p>Of course I could write a CLR stored proc to do the export, seems like overkill though. (Why is this even hard?)</p> <pre><code>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 ^&lt;?xml version="1.0" ?^&gt; &gt; ' + @FileName SET @AppendXmlBody = 'TYPE ' + @FileName + '.tmp &gt;&gt; ' + @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 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload