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

前端 未结 2 2029
慢半拍i
慢半拍i 2020-12-29 17:13

I have a table which has an IDENTITY field and a VARBINARY(MAX) field in it. Is there any way I could dump the content of each VARBINARY(MAX)

相关标签:
2条回答
  • 2020-12-29 17:45

    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!

    0 讨论(0)
  • 2020-12-29 18:00

    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.

    0 讨论(0)
提交回复
热议问题