views:

1146

answers:

2

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) field to the filesystem (eg. c:\temp\images)?

Table schema:

PhotoId INTEGER NOT NULL IDENTITY
Image VARBINARY(MAX) NOT NULL
DateCreated SMALLDATETIME

Output:

c:\temp\images\1.png
c:\temp\images\2.png
c:\temp\images\3.png
... etc...

What is the best way to approach this?

EDIT: Answered own question -> so i've moved the answer, below.

A: 

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.

Boo
So if i have a new 'filestream' column, how to i export that content files using t-sql instead of making a .NET application?
Pure.Krome
Upvoting it just to get it off the "Unanswered" screen.
Brent Ozar
A: 

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!

Pure.Krome