写UTF-8和xp_cmdshell到文件(Write to file with xp_cmdshe

2019-07-29 15:20发布

我创建的文件和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编码的文件?

Answer 1:

您可以使用SQLCMD而不是旧tecnique如DOS outupt重定向

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

PS我不能测试它,请检查SQLCMD文档

希望它能帮助



Answer 2:

我终于成功通过写输出到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;


文章来源: Write to file with xp_cmdshell in UTF-8