How To Save XML Query Results to a File(如何将 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 查询结果保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 XML 查询结果保存到文件
基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
