Issue with using a SELECT statement with OPENROWSET function

Hello

I use the following SELECT stategemt when I try to upload a file from a local path into a table that has a varbinary(MAX) column:

SELECT BulkColumn FROM OPENROWSET(BULK 'D:\MyFolder\Image01.bmp', SINGLE_BLOB) rs

Open in new window


This works for me, however; there is a need for me to pass the 'D:\MyFolder\Image01.bmp' as a variable in the SELECT statement above. For example:

DECLARE @MY_VAR VARCHAR(100)
SELECT @MY_VAR = 'D:\MyFolder\Image01.bmp'
SELECT BulkColumn FROM OPENROWSET(BULK @MY_VAR, SINGLE_BLOB) rs

Open in new window


When I do this and run the query, I get the following error message from the server:

Incorrect syntax near '@MY_VAR'

Any idea why and how to resolve this using a variable that carries the path rather than passing the path itself in the SELECT statement?
Hussein ZahranAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Barry CunneyCommented:
Hi Hussein,
I think you may have to do this using dynamic SQL, as OPENROWSET expects literals and not expressions.
So something similar to the following may be possible:
DECLARE @MY_VAR VARCHAR(100)
DECLARE @SQL NVARCHAR(MAX)


SELECT @MY_VAR = 'D:\MyFolder\Image01.bmp'

SET @SQL ='SELECT BulkColumn FROM OPENROWSET(BULK ' + @MY_VAR + ', SINGLE_BLOB) rs'

PRINT @SQL

--EXEC(@SQL)

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Vitor MontalvãoMSSQL Senior EngineerCommented:
Hussein, do you still need help with this question?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.