I am trying to insert file through SQL. I use following query.
INSERT INTO [dbo].[Attachments] (FileName, FileBinary)
SELECT
'non-date-in-sql-server-column',
BulkColumn
FROM
OPENROWSET(Bulk 'C:\Users\Pictures\Picture.JPG', SINGLE_BLOB) AS BLOB
It's working fine.
I want to write the procedure that take dynamic path. Its giving me error that I cannot take Filebinary in addin. Which is datatype varbinary. What is the best way to do ?
I have done following but its not taking properly binary value.
DECLARE @SQLString NVARCHAR(MAX)
SET @SQLString = 'SELECT ' + '''' +@Filename +'''' + ' AS Name,' + 'FileBinary
FROM OPENROWSET(BULK N''' + @ImagePath + ''',SINGLE_BLOB) AS FileBinary(FileBinary);'
Insert Into Attachments (ApplicantID, FileName, FileBinary)
Values (@ApplicantID, @FileName, Convert(varbinary(max), @SQLString))
Put the Insert statement inside a dynamic query and execute it.
Now your @SQLString
will not have the FileBinary
value it will have the dynamically framed string . You need to execute it to get the values
DECLARE @SQLString NVARCHAR(MAX),
@Filename VARCHAR(500), -- Pass file name here
@ApplicantID VARCHAR(500) --Pass Application ID here
SET @SQLString = '
Insert Into Attachments
(
ApplicantID,
FileName,
FileBinary
)
SELECT @ApplicantID,@Filename,FileBinary
FROM OPENROWSET(BULK N''' + @ImagePath
+ ''',SINGLE_BLOB) AS FileBinary(FileBinary);'
EXEC Sp_executesql
@SQLString,
N'@Filename varchar(500),@ApplicantID varchar(500)',
@Filename =@Filename,
@ApplicantID=@ApplicantID
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With