如何将 XML 查询结果保存到文件 [英] How To Save XML Query Results to a File

查看:47
本文介绍了如何将 XML 查询结果保存到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an SQL query and I am using For XML Path to generate the result as an XML.

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

Can anyone help me about converting that XML output into "a.xml" file and save in a particular folder of a computer?

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

Also want to know, is there any method other than BCP to achieve this?

推荐答案

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

You could try using 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 命令,例如设置编码...

You could also try a Powershell command if you wanted a bit more control e.g. to set encoding...

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

一些注意事项...

该命令有 8000 个字符的长度限制,因此不适用于大文件.

There is an 8000 character length limit on the command, so it's no good for large files.

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

If you save the file to a mapped drive, it will look for that drive on the database server. So, C:\ will be referring to the C:\ drive of the server, not where you are running Management Studio.

运行xp_cmdshell需要特殊权限.

点击此处了解更多详情.

Click here for more details.

这篇关于如何将 XML 查询结果保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆