troubleshooting Question

SQL statements with variables

Avatar of TimHudspith
TimHudspith asked on
Microsoft SQL Server
4 Comments1 Solution309 ViewsLast Modified:
I have a SQL statement that uploads an image file to a FILESTREAM column in SQL server. If I want to introduce variables into this statement, rather than literal values, I understand that I need to produce a dymamic SQL statement, then EXEC that statement. I can't seem to get the syntax right though.

Original (this works ok):

INSERT INTO T_Photos (UI, Filename, Location, Photo)
SELECT newid(), 'myImage.JPG', 'London', Photo.*

My attempt using variables:

@Filename as varchar(20) = 'myImage.JPG',
@Location as varchar(20) = 'London',
@Filepath as varchar(100) =  'C:\myPath\myImage.jpg',
@UI as uniqueidentifier = NEWID(),
@sql as varchar(1000)

SET @sql =
'INSERT INTO T_Photos (UI, Filename, Location, Photo)' +
'SELECT ' + CONVERT(char(255),@UI) + ', ''' + CONVERT(varchar,@Filename) +''', ''' +
CONVERT(varchar,@Location) + ''', Photo.* ' +
'FROM OPENROWSET (BULK ''' + CONVERT(varchar, @Filepath) + ''', SINGLE_BLOB) Photo'

EXEC @sql

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros