1

I am trying to create a query script for SQL Server that will convert pdf file into varbinary data and store it into the SQL Table column which is varbinary(max). I also have to make sure it loops so it can do that for the next pdf file in that folder. This folder will only contain pdf files.

DECLARE @pdf VARBINARY(MAX)

SELECT @pdf = BulkColumn
FROM OPENROWSET(BULK N'C:\Users\......\YourFile.pdf', SINGLE_BLOB) AS Document;

SELECT @pdf, DATALENGTH(@pdf)

INSERT INTO dbo.YourTable(PDFContents) VALUES(@Pdf)
GO

How to put .pdf file contents into varbinary(max) colunm

5
  • 2
    Why do you need to do this in a query? Surely it is much, much, much easier to do this from C# or Powershell... Commented Jul 6, 2016 at 16:25
  • I don't have to do a Query but I do have to find a solution that is automated. I have put the pdf files on a certain location. Run a procedure and it will complete the task. How would I go about complete this task using C# or even Powershell. I will have to make this procedure automated, so I don't have to go in and alter the code Commented Jul 6, 2016 at 16:35
  • To enumerate all files use master.sys.xp_dirtree stored proc.
    – Serg
    Commented Jul 6, 2016 at 17:20
  • In the future use t-sql for sql-server
    – paparazzo
    Commented Jul 7, 2016 at 14:41
  • Filetable (filestream with 2008 R2) may be a solution. technet.microsoft.com/en-us/library/bb933995(v=sql.105).aspx Commented Jul 7, 2016 at 15:15

2 Answers 2

1

So it sounds like you do not have to parse the pdf, just import the entire thing into one column. If so, you could try using SSIS. Create a data flow task and use the Import Column transformation, this should allow you to import the pdf as an image; you'd just need to specify the path to your files. As far as processing several files in the folder, create a ForEach Loop for the data flow task. And for the automation part, just schedule the ssis package via sql jobs to run at specific times or on a regular schedule.

0

Assume you have SQLPS installed (in sql server 2012+, it is called SQLPS MODULE but in SQL Server 2008 R2, it is called SQLPS SnapIns)

You can run the following one-line PS to solve your problem. (I run it in my local computer, which has a DEFAULT sql server instance)

Here is the table I created for holding my PDF files

use tempdb 
create table dbo.tblPDF (id int identity, pdf varchar(max));

Here is PS line

dir c:\test\*.pdf | % { [string]$query = "insert into tempdb.dbo.tblPDF (pdf) select x from openrowset (bulk N'$($_)', SINGLE_BLOB) as T(x)"; INVOKE-SQLCMD -SERVER . -Database tempdb -Query $query -QueryTimeout 3600};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.