I\'m trying to insert an image in SQL server but I got this error :
Cannot bulk load. The file "\'+ @imagepath +\'" does not exist or you don\'t ha
As I said in the comment "OPENROWSET
requires a literal string. You'll need to use dynamic SQL and safely inject the value in.":
DECLARE @imagepath nvarchar(255) = N'C:\Temp\YourImage.png', --Obviously you have set elsewhere.
@Id int = 1; --Obviously you have set elsewhere.
DECLARE @SQL nvarchar(MAX),
@CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET @SQL = N'INSERT INTO dbo.test(Id, logo)' + @CRLF +
N'SELECT @Id, BulkColumn' + @CRLF +
N'FROM OPENROWSET(BULK '''+ REPLACE(@imagepath,'''','''''') +''', SINGLE_BLOB) AS img;';
EXEC sys.sp_executesql @SQL, N'@Id int', @Id; --I have guessed the datatype of @Id
It seems to OP isn't familiar with how to CREATE
or ALTER
a procedure; I must admit I find this odd considering that they have a CREATE
statement in their question, but nevermind.
To create or alter a procedure you use the CREATE
or ALTER
command; in more recent versions there is also CREATE OR ALTER
as well.
In simple terms it's like this in psuedo SQL:
CREATE OR ALTER PROC {Your Procedure Name} {Parameters} AS
BEGIN
{Stored Procedure SQL statements}
END;
So, you might want a stored procedure that returns for a specific customer ID; that would be
CREATE OR ALTER PROC dbo.GetCustomer @ID int AS
BEGIN
SELECT CustomerName,
CustomerEmail,
CustomerPhone
FROM dbo.Customer
WHERE ID = @ID;
END;
For what I have you, just do this:
CREATE OR ALTER PROC dbo.InsertImage @ID int, @imagepath nvarchar(255) AS
BEGIN
DECLARE @SQL nvarchar(MAX),
@CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET @SQL = N'INSERT INTO dbo.test(Id, logo)' + @CRLF +
N'SELECT @Id, BulkColumn' + @CRLF +
N'FROM OPENROWSET(BULK '''+ REPLACE(@imagepath,'''','''''') +''', SINGLE_BLOB) AS img;';
EXEC sys.sp_executesql @SQL, N'@Id int', @Id; --I have guessed the datatype of @Id