SQL Server导出Blob损坏所有文件

时间:2019-06-20 12:47:01

标签: sql sql-server blob ole

我正在使用以下代码导出Blob:

sp_configure 'Ole Automation Procedures', 1;  
GO  
RECONFIGURE;  
GO

DECLARE @outout_path varchar(50) = 'D:\blob',
        @i bigint,
        @init int,
        @data varbinary(max),
        @file_path varchar(max),
        @folder_path  varchar(max)

DECLARE @Doctable TABLE (id int identity(1,1) , [FileName]  varchar(100), file_data varBinary(max) )

INSERT INTO @Doctable([FileName],file_data)
Select top 10 thefilename, file_data FROM  schm.table_with_blobs

SELECT @i = COUNT(1) FROM @Doctable

WHILE @i >= 1
BEGIN

    SELECT @data = [file_data],
           @file_path = @outout_path + '\'+ cast(id as varchar) + '\' + [FileName],
           @folder_path = @outout_path + '\'+ cast(id as varchar)
    FROM @Doctable
    WHERE id = @i

  EXEC [dbo].[CreateFolder]  @folder_path

  EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT;
  EXEC sp_OASetProperty @init, 'Type', 1; 
  EXEC sp_OAMethod @init, 'Open';
  EXEC sp_OAMethod @init, 'Write', NULL, @data;
  EXEC sp_OAMethod @init, 'SaveToFile', NULL, @file_path, 2;
  EXEC sp_OAMethod @init, 'Close';
  EXEC sp_OADestroy @init;

  print 'Document Generated at - '+  @file_path  

SELECT @data = NULL,
       @init = NULL,
       @file_path = NULL,
       @folder_path = NULL;

SET @i -= 1;
END

所有文件均按预期格式导出。但是,无论文件格式如何,所有文件都已损坏且无法打开。我该如何避免这种情况?我是否需要更明确地调出文件类型(在thefilename字段中可用)?

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,但是使用BCP而不是使用ADODB进行导出。 我必须做两件事:

  • 将varbinary转换为varchar或nvarchar
  • 将BCP导出为 RAW

这是我想出的BCP解决方案:

Declare @patient int, @mincount int, @maxcount int,@filename varchar(200), @script varchar(2000),@fileid varchar(10)

Set @patient=2;
set @mincount=1;

Declare @mydocs as table
(filename varchar(255), filebody image, drank int, file_id int)
insert into @mydocs
Select taf.Attachment_File_Name, taf.Attachment_File_Body, DENSE_RANK() OVER (ORDER BY taf.attachment_file_id) as drank, taf.Attachment_File_ID FROM [CNGSTT].[dbo].[tblAttachment] ta 
left join  [CNGSTT].[dbo].[tblAttachmentFile] taf 
on taf.Attachment_ID=ta.Attachment_ID where ta.Patient_ID=@patient

Set @maxcount=(select MAX(drank) from @mydocs)

WHILE @mincount<=@maxcount
BEGIN

Set @filename = (select fle.FileName from @mydocs fle where drank=@mincount)
Set @fileid =(select fle.File_id from @mydocs fle where drank=@mincount)

set @script = 'bcp "SELECT cast(cast(Attachment_File_Body as varbinary(max)) as varchar(max)) from [tblattachmentfile] fle where Attachment_File_ID='+@fileid+'" queryout D:\temp\' + @filename + ' -T -c -C RAW'

exec master..xp_cmdshell @script
Set @mincount=@mincount+1
END