sql-server – 使用BCP创建XML文件会生成对非ASCII字符使用无效编码的文件

再现问题,SQL代码:

CREATE TABLE dbo.FooTable(SomeString NVARCHAR(100));
INSERT INTO dbo.FooTable(SomeString)
VALUES('Degree symbol is °');
DECLARE @Code NVARCHAR(4000) = N'BCP "SELECT (SELECT SomeString FROM dbo.FooTable FOR XML PATH(''Foo''), ROOT(''BAR''), TYPE )"  QUERYOUT "F:\Output\File.XML" -c -C RAW -T ';

EXEC xp_cmdshell @Code;

DROP TABLE dbo.FooTable;

它创建包含以下内容的文件:

<BAR><Foo><SomeString>Degree symbol is °</SomeString></Foo></BAR>

Internet Explorer和Firefox不会将此类文件识别为有效的XML文件(Chrome在第23行的第1行产生错误错误:编码错误).如果我用记事本打开它们并保存为Unicode(小端) – 它会打开并验证.

更新:

changing bcp options to -T -w -r -t seems to make XML valid for most XML consumers, but not Internet Explorer.

最佳答案 试试这个 –

IF OBJECT_ID('tempdb.dbo.##t') IS NOT NULL
    DROP TABLE ##t

SELECT x = (
    SELECT x
    FROM (
        VALUES (N'Degree symbol is °')
    ) t(x)
    FOR XML PATH('Foo'), ROOT('BAR'), TYPE
)
INTO ##t

DECLARE @sql NVARCHAR(4000) = 'bcp "SELECT * FROM ##t" queryout "D:\sample.xml" -S ' + @@servername + ' -T -w -r -t'
EXEC sys.xp_cmdshell @sql

只是有趣的问题根源在哪里……

点赞