[英]Export data to csv files using sqlcmd with special characters in SQL Server
I am facing an issue while exporting data from a table to CSV
file format using SQLCMD
using SQL Query.我在使用
SQLCMD
使用 SQL 查询将数据从表导出为CSV
文件格式时遇到问题。 The issue is with the data which contains special characters like degree Celsius ( °
) or ®
.问题在于包含特殊字符(如摄氏度 (
°
) 或®
。 The output is being converted to another value like ø
.输出正在转换为另一个值,如
ø
。 Please find the below query string which I am using.请找到我正在使用的以下查询字符串。
EXEC xp_cmdshell 'sqlcmd -s, -W -Q "set nocount on; select * from ##XMLData_Output ORDER BY SKU_NUMBER" | findstr /v /c:"-" /b > "c:\Scripts\PED_Attributes.csv"'
The data in ##XMLData_Output is ##XMLData_Output 中的数据是
After exporting the data, the output file looks like导出数据后,输出文件看起来像
Is there a way to get the output in the csv exactly like the input data?有没有办法让 csv 中的输出与输入数据完全一样? I have tried using multiple options like adding -f 65001 with no luck.
我尝试使用多个选项,例如添加 -f 65001 ,但没有运气。 I am using
SQLCMD
because I need to export the column names along with the data.我使用
SQLCMD
是因为我需要将列名与数据一起导出。 If we can fix the issue in SQLCMD
, it would be great.如果我们能在
SQLCMD
解决这个问题,那就太好了。 If we have another option to export the data from SQL Server to csv
through some other way like bcp
that would be also great.如果我们有另一种选择,可以通过
bcp
等其他方式将数据从 SQL Server 导出到csv
,那也很棒。 Please help me to fix this issue.请帮我解决这个问题。 Any help will be appreciated.
任何帮助将不胜感激。
You can add the -f
parameter to your call to sqlcmd to specify codepages for input and output.您可以将
-f
参数添加到对 sqlcmd 的调用以指定输入和输出的代码页。
Its syntax is它的语法是
-f codepage | i:codepage[,o:codepage] | o:codepage[,i:codepage]
so for example:所以例如:
EXEC xp_cmdshell 'sqlcmd -s, -W -f 1252 -Q "set nocount on; select * from ##XMLData_Output ORDER BY SKU_NUMBER" | findstr /v /c:"-" /b > "c:\Scripts\PED_Attributes.csv"'
or或者
EXEC xp_cmdshell 'sqlcmd -s, -W -f o:65001 -Q "set nocount on; select * from ##XMLData_Output ORDER BY SKU_NUMBER" | findstr /v /c:"-" /b > "c:\Scripts\PED_Attributes.csv"'
(see sqlcmd doc at https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility?view=sql-server-ver15 and list of codepages at https://docs.microsoft.com/en-us/windows/win32/intl/code-page-identifiers ) (见SQLCMD文档https://docs.microsoft.com/en-us/sql/tools/sqlcmd-utility?view=sql-server-ver15在和代码页的列表https://docs.microsoft.com/en -us/windows/win32/intl/code-page-identifiers )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.