How to export image field to file?

后端 未结 4 1035
独厮守ぢ
独厮守ぢ 2020-11-29 06:48

I am using Microsoft SQL Server Management Studio to connect to a database. In it I\'ve got a table, one column of which is an Image column containing file data. Another col

4条回答
  •  长情又很酷
    2020-11-29 07:32

    -- Write database image (jpg) to file
    -- http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=101754
    --------- --------- --------- --------- --------- --------- --------- 
    DECLARE @ImageData varbinary(max);
    SELECT @ImageData = (SELECT convert(varbinary(max), ImageData, 1) FROM ProductImages WHERE Id = 1);
    
    DECLARE @Path nvarchar(1024);
    SELECT @Path = 'C:\MyImages\Output';
    
    DECLARE @Filename NVARCHAR(1024);
    SELECT @Filename = (SELECT ImageFilename FROM ProductImages WHERE id = 1);
    
    DECLARE @FullPathToOutputFile NVARCHAR(2048);
    SELECT @FullPathToOutputFile = @Path + '\' + @Filename;
    
    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;
    
    -- Make sure the following statement is executed to enable file IO
    -- From http://msdn.microsoft.com/en-us/library/ms191188.aspx
    --------- --------- --------- --------- --------- --------- --------- 
    sp_configure 'show advanced options', 1;
    GO
    RECONFIGURE;
    GO
    sp_configure 'Ole Automation Procedures', 1;
    GO
    RECONFIGURE;
    GO
    

    PS - The link to article 'Reading and Writing Files in SQL Server using T-SQL' was useful but I after I got the piece of code working it produced an invalid image file.

提交回复
热议问题