How to dump all of our images from a VARBINARY(MAX) field in SQL Server 2008 to the filesystem?

╄→尐↘猪︶ㄣ 提交于 2019-11-30 05:31:57

I've figured it out thanks to this post ...

SET NOCOUNT ON

DECLARE @IdThumbnail INTEGER,
        @MimeType VARCHAR(100),
        @FileName VARCHAR(200),
        @Sqlstmt varchar(4000)


DECLARE Cursor_Image CURSOR FOR
    SELECT a.IdThumbnail
    FROM tblThumbnail a
    ORDER BY a.IdThumbnail

OPEN Cursor_Image
    FETCH NEXT FROM Cursor_Image INTO @IdThumbnail

    WHILE @@FETCH_STATUS = 0
    BEGIN

        -- Generate the file name based upon the ID and the MIMETYPE.
        SELECT @FileName = LTRIM(STR(@IdThumbnail)) + '.png'

        -- Framing DynamicSQL for XP_CMDshell            
        SET @Sqlstmt='BCP "SELECT OriginalImage 
                      FROM Appian.dbo.tblThumbnail 
                      WHERE IdThumbnail = ' + LTRIM(STR(@IdThumbnail)) +
                      '" QUERYOUT c:\Temp\Images\' + LTRIM(@FileName) + 
                      ' -T -fC:\Temp\ImageFormatFile.txt'
        print @FileName
        print @sqlstmt

        EXEC xp_cmdshell @sqlstmt
        FETCH NEXT FROM Cursor_Image INTO @IdThumbnail
    END

CLOSE Cursor_Image
DEALLOCATE Cursor_Image

Please note -> u need to have a format file, for the BCP command. This is the content of the file and i've placed it in c:\Temp (as noted in the BCP commandline above).

10.0
1
1       SQLIMAGE            0       0       ""   1     OriginalImage                      ""

Final note about that format file .. there HAS TO BE A NEW LINE AFTER THE LAST LINE. otherwise u'll get an error.

Enjoy!

The easiest (for me) would be to write a little .NET application that dumped the varbinary fields to a file.

If you are opposed to working in .NET, then you should (I've not tested this) be able to create a new column of type "VARBINARY(MAX) FILESTREAM". Be sure you also have a the corresponding "ROWGUIDCOL" column. Then you can (in theory) do something like:

UPDATE table SET varfilestream_col = varbinary_col

Hope that works for ya.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!