【问题标题】:How To Save XML Query Results to a File如何将 XML 查询结果保存到文件
【发布时间】:2013-09-12 22:00:18
【问题描述】:

我有一个 SQL 查询,我正在使用 For XML Path 将结果生成为 XML。

谁能帮我将 XML 输出转换为“a.xml”文件并保存在计算机的特定文件夹中?

也想知道,除了BCP还有什么方法可以实现吗?

【问题讨论】:

  • 你用的是哪个客户端?
  • 我正在使用 sql server management studio 2012

标签: sql-server xml


【解决方案1】:

您可以尝试使用xp_cmdshell....

-- Read your query results into an XML variable
DECLARE @xml AS XML = (SELECT * FROM YourTable FOR XML PATH)

-- Cast the XML variable into a VARCHAR
DECLARE @xmlChar AS VARCHAR(max) = CAST(@xml AS VARCHAR(max))

-- Escape the < and > characters
SET @xmlChar = REPLACE(REPLACE(@xmlChar, '>', '^>'), '<', '^<')

-- Create command text to echo to file
DECLARE @command VARCHAR(8000) = 'echo ' + @xmlChar + ' > c:\test.txt'

-- Execute the command
EXEC xp_cmdshell @command

如果您想要更多控制权,也可以尝试使用 Powershell 命令,例如设置编码...

DECLARE @command VARCHAR(8000) = 'powershell -Command "Set-Content -Encoding UTF8 C:\test.txt \"' + @xmlChar + '\""'

一些笔记...

该命令有 8000 个字符的长度限制,所以它不适合大文件。

如果您将文件保存到映射驱动器,它将在数据库服务器上查找该驱动器。因此,C:\ 将指的是服务器的 C:\ 驱动器,而不是您运行 Management Studio 的位置。

运行xp_cmdshell需要特殊权限。

点击here了解更多详情。

【讨论】:

  • 这正是我想要的
  • 多么好的答案,我花了几天时间试图找到这个解决方案,当我找到这个答案时,我的问题在几秒钟内就解决了。哇谢谢@davmos
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多