问题描述
下面是一个非常小的 SQL 和 XML 示例,但不知道如何将其导出到 C:\Users\Simon.Evans\Documents\Test.xml.公平地说,我对 XML 的了解很少甚至为零,所以在黑暗中行走.最终,我试图找到一种将 SQL 表导出到 XML 文件的方法.
Below is a very small example of the SQL and XML but no idea how to export this into say C:\Users\Simon.Evans\Documents\Test.xml. To be fair I have very little to zero knowledge of XML so walking in the dark. Ultimately I am trying to find a way to export for SQL tables into an XML file.
SELECT
patient.OID AS '@ID',
patient.FORENAME, patient.SURNAME,
patient.TITLECODE,
patient.BIRTHDTTM
FROM
HealthBI.dbo.LZO_PATIENT patient
WHERE patient.OID = '3400000000'
FOR XML PATH('Patient'), ROOT('Patient')
而sql的XML输出是:
and the XML output of the sql is:
<Patient>
<Patient ID="3400000000">
<FORENAME>IDA</FORENAME>
<SURNAME>CARR</SURNAME>
<TITLECODE>CC_MRS</TITLECODE>
<BIRTHDTTM>1929-10-25T00:00:00</BIRTHDTTM>
</Patient>
</Patient>
推荐答案
将 XML 查询到文件中需要了解一点字符编码...
Querying XML into a file needs to know a little bit about character encoding...
试试这个:
USE master;
GO
CREATE DATABASE TestDB;
GO
CREATE TABLE TestDB.dbo.TestTbl(TestString1 VARCHAR(100),TestString2 NVARCHAR(100));
INSERT INTO TestDB.dbo.TestTbl VALUES('abc', N'abc')
,('<&> Russian: "слов в тексте"', N'<&> Russian: "слов в тексте"');
GO
SELECT * FROM TestDB.dbo.TestTbl FOR XML PATH('Test'),ROOT('String');
/* The result of the simple SELECT shows, that VARCHAR cannot deal with russian letters
<String>
<Test>
<TestString1>abc</TestString1>
<TestString2>abc</TestString2>
</Test>
<Test>
<TestString1><&> Russian: "???? ? ??????"</TestString1>
<TestString2><&> Russian: "слов в тексте"</TestString2>
</Test>
</String>
*/
GO
--Two times the same command, only difference is -w instead of -c:
--And: YOU HAVE TO FULLY QUALIFY THE OBJECT's NAME!
DECLARE @cmd1 VARCHAR(4000)='bcp "SELECT * FROM TestDB.dbo.TestTbl FOR XML PATH(''object''),ROOT(''objects'');" queryout "c:\dvp\test1.xml" -T -c -S' + @@SERVERNAME;
DECLARE @cmd2 VARCHAR(4000)='bcp "SELECT * FROM TestDB.dbo.TestTbl FOR XML PATH(''object''),ROOT(''objects'');" queryout "c:\dvp\test2.xml" -T -w -S' + @@SERVERNAME;
EXECUTE master..xp_cmdshell @cmd1;
EXECUTE master..xp_cmdshell @cmd2;
GO
DROP DATABASE TestDb;
GO
使用 -c
的第一个命令的结果现在即使使用 NVARCHAR
The result of the first command with -c
will now destroy the russian letters even with NVARCHAR
<objects>
<object>
<TestString1>abc</TestString1>
<TestString2>abc</TestString2>
</object>
<object>
<TestString1><&> Russian: "???? ? ??????"</TestString1>
<TestString2><&> Russian: "???? ? ??????"</TestString2>
</object>
</objects>
带有 -w
的第二个命令的结果符合预期:
The result of the second command with -w
is as expected:
<objects>
<object>
<TestString1>abc</TestString1>
<TestString2>abc</TestString2>
</object>
<object>
<TestString1><&> Russian: "???? ? ??????"</TestString1>
<TestString2><&> Russian: "слов в тексте"</TestString2>
</object>
</objects>
这篇关于能否将 SQL Server 2012 数据导出到 XML 文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!