Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert file to SQL Server without front end using stored procedure

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))
like image 546
arti Avatar asked Oct 31 '22 08:10

arti


1 Answers

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 
like image 70
Pரதீப் Avatar answered Nov 08 '22 15:11

Pரதீப்