How can I specify the path to a file dynamically in OPENROWSET(BULK…)?

后端 未结 1 375
滥情空心
滥情空心 2021-01-14 02:57

I want to insert images into an Image field, preferably using a stored procedure which will accept a path to an image. After hacking around I came up with this;



        
1条回答
  •  时光说笑
    2021-01-14 03:49

    You do have to use dynamic sql but you can use quotename() to avoid embedded quote nightmares and you should pass the primary key in as an actual parameter.

    DECLARE @sql_string nvarchar(max) = 
    N'UPDATE MyTable
      SET MyImageField = (SELECT BulkColumn 
                          FROM Openrowset(Bulk ' + quotename(@PathToMyImage,nchar(39)) + ', Single_Blob) ImageData)
      WHERE MyPrimaryKey = @PrimaryKey';
    
    EXECUTE sp_executesql @sql_string, N'@PrimaryKey int',  @PrimaryKey
    

    nchar(39) is a single quote. All single quotes within the path name will be properly escaped and the path will be enclosed in single quotes for safe concatenation.

    0 讨论(0)
提交回复
热议问题