Cannot bulk load. The file “'+ @imagepath +'” does not exist or you don't have file access rights

后端 未结 1 1586
别跟我提以往
别跟我提以往 2021-01-23 10:53

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

相关标签:
1条回答
  • 2021-01-23 11:38

    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
    
    0 讨论(0)
提交回复
热议问题