4

I am trying to insert a pdf file into a sql table (varbinary column)

create table pdfTest(pdfData varbinary(max))
declare @filePath varchar(100)
set @filePath = 'c:\pdfSample.pdf'
INSERT INTO pdfTest (pdfData) SELECT * FROM OPENROWSET(BULK @filePath, SINGLE_BLOB) AS BLOB

However this gives an error

 Incorrect syntax near '@filePath'.

None of the following assignment works

 set @filePath = 'c:'\pdfSample.pdf'
 set @filePath = 'c:\\pdfSample.pdf'

But the following syntax works

 INSERT INTO pdfTest (pdfData) SELECT * FROM OPENROWSET(BULK 'c:\pdfSample.pdf', SINGLE_BLOB) AS BLOB

Just wondering how @filePath can be used in the insert statement?

Thank you

2 Answers 2

4

I think here the variable name is not getting resolved. Try using the variable name in dynamic sql.

 Declare @sql varchar(max)
 Set @sql='INSERT INTO pdfTest (pdfData) SELECT * FROM OPENROWSET(BULK'+ @filePath+', SINGLE_BLOB) AS BLOB'
 exec @sql
Sign up to request clarification or add additional context in comments.

3 Comments

This gives error: Could not find stored procedure 'INSERT INTO pdfTest (pdfData) SELECT * FROM OPENROWSET(BULKc:\pdfSample.pdf, SINGLE_BLOB) AS VARBINARY'. it's removing the single quotes from the filePath
@bluepiranha, just change exec @sql to exec(@sql)
@bluepiranha, and OPENROWSET(BULK'+ @filePath+', SINGLE_BLOB) to OPENROWSET(BULK'''+ @filePath+''', SINGLE_BLOB)
-1
Declare @sql nvarchar(max)
 Set @sql='INSERT INTO pdfTest (pdfData) SELECT * FROM OPENROWSET(BULK '''+ @filePath+''', SINGLE_BLOB) AS BLOB'
 exec sp_executesql  @sql

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.