我正在使用 SELECT ... FOR XML 来生成 XML,它创建的正是我想要看到的 -在 SSMS 中。但...
我遇到的问题是,导出的 XML 文件将整个 XML 正文放在一行上。它是有效的 XML,但如何格式化输出?(每行一个元素,以 \r\n 结尾,最好缩进)该文件应该在记事本中可读。
另外,是否有更好的方法来附加 XML 标头?
当然,我可以编写一个 CLR 存储过程来进行导出,但这似乎有点矫枉过正。(为什么这更难?)
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