简体   繁体   中英

OPENROWSET - Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query

Hi I am trying to insert results of a stored procedure into a table called MyBinaryTable. MyBinaryTable contains two columns: (FileId [type:int], and BulkColumn [type:varbinary(max)]). The stored procedure returns two columns called FileId and BulkColumn. When Inserting the values into MyBinaryTable from the stored procedure, I am greeted with this error:

Implicit conversion from data type varchar to varbinary(max) is not allowed. 
Use the CONVERT function to run this query.

Here is my stored procedure:

CREATE PROCEDURE [dbo].[GenerateBinary] @Route VARCHAR(300), @FileId 
VARCHAR(10)
AS
Declare @sql varchar(max)
Set @sql='SELECT convert(varbinary(max),((SELECT BulkColumn FROM OPENROWSET( 
BULK ''' + @Route + ''' , SINGLE_BLOB) as Data)), 0) as ''BulkColumn'',''' + 
@FileId + ''' as ''FileId'''
Print @sql
Exec(@sql)

Here is how I am inserting the values:

INSERT INTO MyBinaryTable
EXEC GenerateBinary 'xyz.docx', @FileId = 254

Do not develop bad habits. You did not specify the column list in the insert statement - that is a bad habit and the cause of our error. The resultset of your procedure is [varbinary(max), varchar(10)]. Is that the same as the structure of your table? No. And you also force another implicit conversion with your fileid argument defined as varchar. So change your procedure to define fileid as int and specify the columns in the insert statement:

insert dbo.MyBinaryTable(BulkColumn, FileId)
select ...;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM