sql-servervarbinarymax

How to pull out data from varbinary(Max) in Microsoft SQL


Problem: I have to pull out data from varbinary columns in MS SQL (PDF).

I have used this script

DECLARE @SQLIMG VARCHAR(MAX),
    @IMG_PATH VARBINARY(MAX),
    @TIMESTAMP VARCHAR(MAX),
    @ObjectToken INT

DECLARE IMGPATH CURSOR FAST_FORWARD FOR 
        SELECT csl_CompanyLogo from mlm_CSCompanySettingsLocalizations

OPEN IMGPATH 

FETCH NEXT FROM IMGPATH INTO @IMG_PATH 

WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @TIMESTAMP = 'd:\' + replace(replace(replace(replace(convert(varchar,getdate(),121),'-',''),':',''),'.',''),' ','') + '.bmp'

        PRINT @TIMESTAMP
        PRINT @SQLIMG

        EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT
        EXEC sp_OASetProperty @ObjectToken, 'Type', 1
        EXEC sp_OAMethod @ObjectToken, 'Open'
        EXEC sp_OAMethod @ObjectToken, 'Write', NULL, @IMG_PATH
        EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, @TIMESTAMP, 2
        EXEC sp_OAMethod @ObjectToken, 'Close'
        EXEC sp_OADestroy @ObjectToken

        FETCH NEXT FROM IMGPATH INTO @IMG_PATH 
    END 

CLOSE IMGPATH
DEALLOCATE IMGPATH

From here Script to save varbinary data to disk

But now i wonder, how can i make file names more readable? For example use records from id column.

P.s. should i place tsql tag?


Solution

  • Add a new variable of the same type as your filename column at the top.

    Change your cursor to select both the varbinary and the filename, and use your new filename variable.

    Use the filename variable when setting the filename in your script, instead of the date.

    Your script becomes:

    DECLARE @SQLIMG VARCHAR(MAX),
        @IMG_PATH VARBINARY(MAX),
        @TIMESTAMP VARCHAR(MAX),
        @ObjectToken INT,
        @Filename varchar(max)
    
    DECLARE IMGPATH CURSOR FAST_FORWARD FOR 
            SELECT csl_CompanyLogo, [filename] from mlm_CSCompanySettingsLocalizations
    
    OPEN IMGPATH 
    
    FETCH NEXT FROM IMGPATH INTO @IMG_PATH , @Filename
    
    WHILE @@FETCH_STATUS = 0
        BEGIN
            SET @TIMESTAMP = 'd:\' + @Filename + '.bmp'
    
            PRINT @TIMESTAMP
            PRINT @SQLIMG
    
            EXEC sp_OACreate 'ADODB.Stream', @ObjectToken OUTPUT
            EXEC sp_OASetProperty @ObjectToken, 'Type', 1
            EXEC sp_OAMethod @ObjectToken, 'Open'
            EXEC sp_OAMethod @ObjectToken, 'Write', NULL, @IMG_PATH
            EXEC sp_OAMethod @ObjectToken, 'SaveToFile', NULL, @TIMESTAMP, 2
            EXEC sp_OAMethod @ObjectToken, 'Close'
            EXEC sp_OADestroy @ObjectToken
    
            FETCH NEXT FROM IMGPATH INTO @IMG_PATH , @Filename
        END 
    
    CLOSE IMGPATH
    DEALLOCATE IMGPATH