Sql-server – Exporting Images from Sql server database into local drive

sql server

My comand:

EXEC master..xp_cmdshell 'BCP "SELECT column_of_type_image FROM **your_db WHERE id = 1 " queryout "C:\exportdir\yourfile.pdf" -T -N'

above query run and successfully download the file but images preview not shown
post downloaded that file size is 1 kb only

Best Answer

The bcp native datatype for a SQL image data type column includes a length prefix that won't be recognized by the rendering application. IMHO, bcp is not the right tool for this job and invoking xp_cmdshell in general is a dubious practice from a security perspective.

That being said, one way you could export the binary column contents to a file is with a PowerShell command invoked via xp_cmdshell:

EXEC xp_cmdshell 'PowerShell -Command "$con = New-Object Data.SqlClient.SqlConnection(''Data Source=.;Integrated Security=SSPI'');$con.Open();$cmd = New-Object Data.SqlClient.SqlCommand(''SET TEXTSIZE -1;SELECT column_of_type_image FROM yourdb.dbo.foobar WHERE id = 1;'', $con);[IO.File]::WriteAllBytes(''C:\exportdir\yourfile.pdf'', $cmd.ExecuteScalar());$con.Close()"'