sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
RECONFIGURE;
GO

DECLARE CURSOR_Files CURSOR FOR (

	SELECT CONCAT(DSET_KEY,'_',DSET_REVISION,'.', THUMBNAIL_TYPE ) as [FILE_NAME]
								 FROM FILE_IMAGES 
)

DECLARE @Filename VARCHAR(255) ;

OPEN CURSOR_Files

FETCH NEXT FROM CURSOR_Files INTO @Filename
WHILE (@@FETCH_STATUS <> -1)
BEGIN
  DECLARE @ImageData varbinary(max);
  SELECT @ImageData = (SELECT convert(varbinary(max), THUMBNAIL, 1) FROM FILE_IMAGES WHERE CONCAT(DSET_KEY,'_',DSET_REVISION,'.', THUMBNAIL_TYPE ) = @fileName);

  DECLARE @Path nvarchar(1024);
  SELECT @Path = 'c:\temp\img_files\';

  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;

  FETCH NEXT FROM CURSOR_Files INTO @Filename
END
CLOSE CURSOR_Files
DEALLOCATE CURSOR_Files
GO

sp_configure 'Ole Automation Procedures', 0;
RECONFIGURE;
GO
sp_configure 'show advanced options', 0;
RECONFIGURE;
GO
