I am inserting a .jpg
into a varbinary(max)
column in SQL Server 2012 using the following command:
INSERT INTO Employees
VALUES(5, (SELECT * FROM OPENROWSET(BULK N'C:\4.jpg',SINGLE_BLOB) AS image))
It inserts a record in the table.
Then I used the following command to restore the file from db to file system.
BCP "SELECT pic FROM Employees where id=5" queryout "C:\51.jpg" -N -T
When I try to view the downloaded file using image viewer, I get an error
File is damaged.
Any ideas?
Best How To :
This worked for me: How to export image field to file?
The short version without the cursor looks like this:
DECLARE @ImageData VARBINARY(max)
DECLARE @FullPathToOutputFile NVARCHAR(2048);
SELECT @ImageData = pic FROM Employees WHERE id=5
SET @FullPathToOutputFile = 'C:\51.jpg'
DECLARE @ObjectToken INT
EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT;
EXEC sp_OASetProperty @ObjectToken, 'Type', 1;
EXEC sp_OAMethod @ObjectToken, 'Open';
EXEC sp_OAMethod @ObjectToken, 'Write', NULL, @ImageData;
EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, @FullPathToOutputFile, 2;
EXEC sp_OAMethod @ObjectToken, 'Close';
EXEC sp_OADestroy @ObjectToken;
Before you can do that you have execute this only once in your database:
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
All credits belong to @mathijsuitmegen :) thanks for this working solution