-2

I have a table called ImageValues. In it, I have columns labeled RecordID, ReportID and Image. The image is stored as an IMAGE data type. I want to extract the image to a file and write the file path into another column labeled FilePath. Preferably, the filename would be "RecordID-ReportID"

I am using SQL Server

Can this be done?

Justin Cave
  • 227,342
  • 24
  • 367
  • 384
Michael
  • 5
  • 2
  • The short and useless answer is "Yes, it can be done". *How exactly* depends on what dialect of SQL you're using (Oracle, SQL Server, MySQL, etc.), whether you want to save the files on the DB server or another machine, and whether you want to do it from SQL or another programming language. If you added more detail to your question, someone might help. – Mihai Jul 19 '15 at 18:58
  • Sorry for the delayed response. The images are actually stored as an Image data type. I am using SQL Server, and the images can be saved to the server (partition E). – Michael Jul 24 '15 at 00:51

1 Answers1

1

One of the ways to do it is using OLE automation, which you can enable if you have administrator privileges on the machine. Here's some sample code, liberally borrowed from this SO answer:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

DECLARE @file int,
        @FilePath varchar(80),
        @hr INT,
        @RecordID INT,
        @ReportID INT,
        @Image VARBINARY(MAX);
DECLARE imgs CURSOR 
    FOR SELECT RecordID, ReportID, "Image" FROM dbo.ImageValues
    FOR UPDATE OF FilePath;

OPEN imgs;  
FETCH NEXT FROM imgs INTO @RecordID, @ReportID, @Image;
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @FilePath = 'E:/' + CAST(@RecordID AS VARCHAR(10)) + '-' + CAST(@ReportID AS VARCHAR(10)) + '.jpg';

    EXEC sp_OACreate 'ADODB.Stream', @file OUT;
    EXEC sp_OASetProperty @file, 'Type', 1;
    EXEC sp_OAMethod @file, 'Open';
    EXEC sp_OAMethod @file, 'Write', NULL, @Image;
    EXEC sp_OAMethod @file, 'SaveToFile', NULL, @FilePath, 2;
    EXEC sp_OAMethod @file, 'Close';
    EXEC sp_OADestroy @file;

    UPDATE dbo.ImageValues SET FilePath = @FilePath WHERE CURRENT OF imgs;

    FETCH NEXT FROM imgs INTO @RecordID, @ReportID, @Image;
END
CLOSE imgs;
DEALLOCATE imgs;
GO

sp_configure 'Ole Automation Procedures', 0;
GO
RECONFIGURE;
GO

Note that all files are going to be stored with the extension '.jpg', but you could extend it to detect the image type based on the magic number.

If you're using SQL Server 2012 or later, you could also use a cool feature called FileTables. Read up on them here, and also here for ways of inserting data into a FileTable using T-SQL. After that, you can simply copy the files wherever you want using Windows Explorer.

Mihai
  • 2,835
  • 2
  • 28
  • 36