如何将 XML 查询结果保存到文件

How To Save XML Query Results to a File(如何将 XML 查询结果保存到文件)
本文介绍了如何将 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 查询结果保存到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)