加入收藏 | 设为首页 | 会员中心 | 我要投稿 鄂州站长网 (https://www.0711zz.com/)- 数据分析、网络、云渲染、应用安全、大数据!
当前位置: 首页 > 数据库 > MsSql > 正文

sql – 将表中的blob导出到单个文件的最快方法

发布时间:2020-07-09 02:07:47 所属栏目:MsSql 来源:互联网
导读:将存储在SQL Server表中的文件(blob)导出到硬盘驱动器上的文件的最快方法是什么?我有超过2.5 TB的文件(90 kb avg)存储为varbinary,我需要尽快将每个文件提取到本地硬盘. BCP似乎可以工作,但是我会看到速度超过45天,而且我担心我的脚本会在某些时候失败,因为M

将存储在SQL Server表中的文件(blob)导出到硬盘驱动器上的文件的最快方法是什么?我有超过2.5 TB的文件(90 kb avg)存储为varbinary,我需要尽快将每个文件提取到本地硬盘. BCP似乎可以工作,但是我会看到速度超过45天,而且我担心我的脚本会在某些时候失败,因为Management Studio会耗尽内存.

解决方法

我尝试使用CLR功能,它的速度是BCP的两倍多.这是我的代码.

原始方法:

SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand

CLR方法:

declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:temp' + @FileName
SELECT Master.dbo.WriteToFile(@file,@filepath,0)

CLR函数的C#代码

using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;

namespace BlobExport
{
    public class Functions
    {
      [SqlFunction]
      public static SqlString WriteToFile(SqlBytes binary,SqlString path,SqlBoolean append)
      {        
        try
        {
          if (!binary.IsNull && !path.IsNull && !append.IsNull)
          {         
            var dir = Path.GetDirectoryName(path.Value);           
            if (!Directory.Exists(dir))              
              Directory.CreateDirectory(dir);            
              using (var fs = new FileStream(path.Value,append ? FileMode.Append : FileMode.OpenOrCreate))
            {
                byte[] byteArr = binary.Value;
                for (int i = 0; i < byteArr.Length; i++)
                {
                    fs.WriteByte(byteArr[i]);
                };
            }
            return "SUCCESS";
          }
          else
             "NULL INPUT";
        }
        catch (Exception ex)
        {          
          return ex.Message;
        }
      }
    }
}

(编辑:鄂州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读