将多个pdf文件导入数据库(文件名=其他列中的值)

时间:2019-03-07 09:23:42

标签: sql sql-server database image pdf

我正在尝试制作一个将多个pdf文件导入数据库的脚本。 我到此为止-一个特定的文件:

DECLARE @pdf VARBINARY(MAX)

SELECT @pdf = BulkColumn
FROM OPENROWSET(BULK N'C:\Users\jd\Desktop\Invoiceimage\999999.pdf', SINGLE_BLOB) AS image;

SELECT @pdf, DATALENGTH(@pdf)

INSERT INTO dbo.CustomerInvoiceImage(InvoiceImage, CustomerInvoiceId) VALUES(@Pdf, '13') 
GO 

它很漂亮。现在,我需要脚本来获取多个文件,并标识文件名,并将其插入“ CustomerInvoiceId”而不是特定的数字13。

1 个答案:

答案 0 :(得分:0)

您可以使用此脚本。仅在必要时才需要启用/禁用xp_cmdshell。更好的解决方案是创建一个以@Folder作为参数的存储过程。

/*
-- enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
*/

DECLARE @Folder AS VARCHAR(MAX)
SELECT @Folder = 'C:\Users\jd\Desktop\Invoiceimage'

DECLARE @Files AS TABLE(Name VARCHAR(MAX))

DECLARE @shellCommand AS VARCHAR(1024)
SELECT @shellCommand = 'DIR ' + @Folder + '\*.pdf /A-D /B'

INSERT INTO @Files(Name)
EXEC master.dbo.xp_cmdshell @shellCommand

DECLARE @Name AS VARCHAR(MAX)

DECLARE C_Files CURSOR FOR
    SELECT Name
    FROM @Files
    WHERE Name IS NOT NULL

OPEN C_Files
FETCH NEXT FROM C_Files INTO @Name

WHILE @@FETCH_STATUS = 0
BEGIN

    DECLARE @CustomerInvoiceId AS INTEGER
    SELECT @CustomerInvoiceId = CAST(LEFT(@Name, CHARINDEX('.', @Name) - 1) AS INTEGER)

    EXEC ('DECLARE @File AS VARBINARY(MAX); '+
        'SELECT @File = BulkColumn FROM OPENROWSET(BULK N''' + @Folder + '\' + @Name + ''', SINGLE_BLOB) AS IMAGE; ' +
        'INSERT INTO CustomerInvoiceImage(InvoiceImage, CustomerInvoiceId) VALUES(@File, ' + @CustomerInvoiceId + ');'
    )

    FETCH NEXT FROM C_Files INTO @Name

END

CLOSE C_Files
DEALLOCATE C_Files

/*
-- disable xp_cmdshell
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 0
GO
RECONFIGURE
GO
*/