【问题标题】:Write to file with xp_cmdshell in UTF-8使用 UTF-8 格式的 xp_cmdshell 写入文件
【发布时间】:2012-05-29 08:02:58
【问题描述】:
我正在使用 xp_cmdshell 创建文件,如下所示:
SELECT @command = 'echo ' + @fileContent + ' > e:\out\' + @fileName + '.csv'
exec master.dbo.xp_cmdshell 'mkdir "e:\out\"'
exec master..xp_cmdshell @command
问题是文件内容不是UTF-8格式,所以一些特殊字符是错误的。
我可以创建 UTF-8 编码的文件吗?
【问题讨论】:
标签:
file
sql-server-2005
utf-8
xp-cmdshell
【解决方案1】:
我终于成功了,将输出写入 temp.txt 文件并添加下一个 PowerShell 命令将其转换为 UTF-8:
-- Change encoding to UTF-8 with PowerShell
SET @command = 'powershell -Command "Get-Content '+@Path+'\temp.txt -Encoding Unicode | Set-Content -Encoding UTF8 '+@path+'\'+@filename+'"';
EXEC xp_cmdshell @command;
【解决方案2】:
您可以使用SQLCMD 代替旧技术作为 DOS 输出重定向
sqlcmd -S ServerName -d DataBaseName -E -o "CSV File Path & Location" -Q "Your Query" -W -w 4000 -s ";" -f 65001
开关-f 65001表示使用UTF8作为outfile文件
SELECT @command = 'sqlcmd -S ServerName -d DataBaseName -E -o "'+ @fileName +'" -Q "Your Query" -W -w 4000 -s ";" -f 65001'
exec master.dbo.xp_cmdshell 'mkdir "e:\out\"'
exec master..xp_cmdshell @command
附言我无法测试它,所以请查看 SQLCMD 文档
希望对你有帮助
【解决方案3】:
我选择了 Jan Lenders 的方式,但在读取时间时没有使用该编码类型设置。
SET @COMMAND = 'powershell -Command "Get-Content '+ @PATH + @V_FILE_NAME + ' | Set-Content -Encoding UTF8 '+ @PATH + @V_FILE_NAME +'2"';
这行得通。
谢谢^^