Avatar of TimHudspith
TimHudspith

asked on 

SQL statements with variables

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.*
FROM OPENROWSET (BULK 'C:\myPath\myImage.JPG', SINGLE_BLOB) Photo


My attempt using variables:

DECLARE
@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
Microsoft SQL Server

Avatar of undefined
Last Comment
TimHudspith

8/22/2022 - Mon