Sql server 如何将多个Word文档批量导入SQL Server数据库表

Sql server 如何将多个Word文档批量导入SQL Server数据库表,sql-server,import,openrowset,Sql Server,Import,Openrowset,我需要将单个目录中的50000 Word文档.doc和.docx导入SQL Server 2016数据库表,以便使用全文索引,然后搜索文档内容 由于这是一项一次性任务,而且数据库不会被需要很长时间,所以我不关心性能,也不关心使用FILESTREAM或FileTables的参数 我刚刚用一个表创建了一个数据库: CREATE TABLE [dbo].[MyDocument] ( [ID] INT IDENTITY(1,1) NOT NULL, [DocumentName] NVAR

我需要将单个目录中的50000 Word文档.doc和.docx导入SQL Server 2016数据库表,以便使用全文索引,然后搜索文档内容

由于这是一项一次性任务,而且数据库不会被需要很长时间,所以我不关心性能,也不关心使用FILESTREAM或FileTables的参数

我刚刚用一个表创建了一个数据库:

CREATE TABLE [dbo].[MyDocument]
(
    [ID] INT IDENTITY(1,1) NOT NULL,
    [DocumentName] NVARCHAR(255) NOT NULL,
    [Extension] NCHAR(10) NOT NULL,
    [DocumentContent] VARBINARY(MAX) NOT NULL,
    CONSTRAINT [PK_MyDocument] PRIMARY KEY CLUSTERED ([ID] ASC)
)
现在,我正在寻找一种方法将我的文档放入表中。在线上有很多使用OPENROWSET将单个文档导入SQL Server数据库表的示例,但它们要求我为文件指定名称,这显然对我的要求没有用处

我真不敢相信没有一个记录良好且直接的方法可以做到这一点,但几个小时的搜索没有发现任何结果,这让我开始怀疑这是否可能,但肯定是吗


有谁能给我一个T-SQL的示例片段,用于将多个文件导入数据库?或者建议如何实现?

下面是一个PowerShell脚本,用于使用参数化查询和FileStream参数值导入指定文件夹中的所有.docx文件,以将文件内容流式传输到数据库,而不是将整个文件内容加载到客户端内存中

# import all documents in specified directory using file stream parameter
try {

    $timer = [System.Diagnostics.Stopwatch]::StartNew()
    $insertQuery = @"
    INSERT INTO dbo.MyDocument (DocumentName, Extension, DocumentContent)
        VALUES(@DocumentName, @Extension, @DocumentContent);
"@
    $connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=YourDatabase;Integrated Security=SSPI")
    $command = New-Object System.Data.SqlClient.SqlCommand($insertQuery, $connection)
    $documentNameParameter = $command.Parameters.Add("@DocumentName", [System.Data.SqlDbType]::NVarChar, 255)
    $documentExtensionParameter = $command.Parameters.Add("@Extension", [System.Data.SqlDbType]::NVarChar, 10)
    $documentContentParameter = $command.Parameters.Add("@DocumentContent", [System.Data.SqlDbType]::VarBinary, -1)
    $connection.Open()

    $filesToImport = Get-ChildItem "E:\DocumentsToImport\*.docx"
    $importedFileCount = 0
    foreach($fileToImport in $filesToImport) {
        $documentContentStream = [System.IO.File]::Open($fileToImport.FullName, [System.IO.FileMode]::Open)
        $documentNameParameter.Value = [System.IO.Path]::GetFileNameWithoutExtension($fileToImport.FullName)
        $documentExtensionParameter.Value = [System.IO.Path]::GetExtension($fileToImport.Name)
        $documentContentParameter.Value = $documentContentStream
        [void]$command.ExecuteNonQuery()
        $documentContentStream.Close()
        $importedFileCount += 1
    }
    $connection.Close()

    $timer.Stop()

    Write-Host "$importedFileCount files imported. Duration $($timer.Elapsed)."
}
catch {
    throw
}

这里有一些powershell,可以将更新插入数据库。我想,你只需要扩展它,在现有文件中循环。。还有一个。再次需要修改以循环浏览源文件。