filesql-server-2005utf-8xp-cmdshell

Write to file with xp_cmdshell in UTF-8


I am creating files with xp_cmdshell like this:

SELECT @command = 'echo ' + @fileContent + ' > e:\out\' + @fileName + '.csv'
exec master.dbo.xp_cmdshell 'mkdir "e:\out\"'
exec master..xp_cmdshell @command 

The problem is that the file contents is not in UTF-8 and so some special characters are wrong.

Can i create the file in UTF-8 encoding?


Solution

  • You can use the SQLCMD instead the old tecnique as DOS outupt redirect

    sqlcmd -S ServerName -d DataBaseName -E -o "CSV File Path & Location" -Q "Your Query" -W -w 4000 -s ";" -f 65001
    

    the switch -f 65001 indicate to use UTF8 as outfile file

    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
    

    p.s. i cant test it so please check the SQLCMD documentation

    Hope it help