我有一个SQL查询,使用For XML Path将结果生成为XML。
请问如何将XML输出转换为“a.xml”文件并保存到计算机的特定文件夹中?
同时想知道是否有除了BCP之外的其他方法可以实现这一点?
我有一个SQL查询,使用For XML Path将结果生成为XML。
请问如何将XML输出转换为“a.xml”文件并保存到计算机的特定文件夹中?
同时想知道是否有除了BCP之外的其他方法可以实现这一点?
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
DECLARE @command VARCHAR(8000) = 'powershell -Command "Set-Content -Encoding UTF8 C:\test.txt \"' + @xmlChar + '\""'
一些注意事项...
该命令有8000个字符长度限制,因此无法处理大型文件。
如果将文件保存到映射驱动器中,则会在数据库服务器上查找该驱动器。因此,C:\ 将指的是服务器的 C:\ 驱动器,而不是您运行 Management Studio 的位置。
要运行 xp_cmdshell
,需要特殊权限。
点击这里了解更多详情。