我正在创建一个插入表的存储过程。以下将提供我的表格列
Create Table Item
(
ID char(20),
Name varchar(max) NOT NULL,
Brand char(10) NOT NULL,
Category char(10) NOT NULL,
Unit_Of_Measure char(5) NOT NULL,
Price decimal(18,2) NOT NULL,
[Image] image NOT NULL,
Active bit NOT NULL Default('True')
Constraint PK_Item Primary Key (ID),
Constraint FK_Item_Brands Foreign Key (Brand) References Brands(ID),
Constraint FK_Item_Item_Category Foreign Key (Category) References Item_Category(ID),
Constraint FK_Item_Unit_Of_Measure Foreign Key (Unit_Of_Measure) References Unit_Of_Measure(ID)
);
go
表插件工作正常。在我们走得更远之前,我需要展示我得到的错误。
Msg 50000,Level 16,State 2,Procedure stpItem,Line 66
不兼容
操作数类型冲突:图像与nvarchar
当我执行下面的命令时,会出现上述错误,之后您将看到存储过程
exec stpItem '','GG','2','2','2',123.12, null, 'true', 'false'
存储过程代码:
Create Proc stpItem
@ID varchar(max),
@Name varchar(max),
@Brand varchar(max),
@Category varchar(max),
@UOM varchar(max),
@Price decimal,
@Image Image,
@Active bit,
@Update bit
As
Set Transaction Isolation Level Serializable
Begin Transaction
Begin Try
-- If it is an insertion
IF @Update = 'False'
Begin
Declare @Pre char(1),
@Len int,
@Next int,
@Start int,
@SetKey varchar(max);
Set @SetKey = '';
Select @Pre = Prefix, @Len = [Length], @Next = [Next] From Key_Generation Where Table_Name = 'Item';
Set @Start = 1;
Set @Len = @Len - 1;
While @Start < @Len
Begin
set @SetKey = @SetKey + '0'
set @Start = @Start + 1;
End
Exec('Declare @LID char(20); Set @LID = (select ''' + @Pre + ''' + right(''' + @SetKey + ''' + cast(' + @Next + ' as varchar(' + @Len + ')), ' + @Len + '));' +
'Insert into Item Values (@LID,''' + @Name + ''',''' + @Brand + ''',''' + @Category + ''',''' + @UOM + ''',' + @Price + ',' + @Image + ' ,' + @Active + ');' +
'Update Key_Generation Set [Next] = [Next] + 1 Where Table_Name = ''Item'';');
End
Else
Begin
Update Item
Set Name = @Name,
[Brand] = @Brand,
[Category] = @Category,
[Unit_Of_Measure] = @UOM,
Price = @Price,
[Image] = @Image,
Active = @Active
Where ID = @ID;
End
Commit Transaction;
End Try
Begin Catch
Rollback Transaction;
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
End Catch
有人能告诉我为什么会收到此错误,以及如何解决此问题?
答案 0 :(得分:0)
您不是在这里将非varchar变量转换为varchar:
@Price + ',' + @Image + ' ,' + @Active + ');'
尝试:
cast(@price as varchar(max)) + ',' + cast(@image as varchar(max)) + ...
答案 1 :(得分:0)
cast(cast(@Image as binary) as nvarchar(max));
我使用nvarchar变量从外部转换它然后在og执行命令
中使用它Declare @txtImage nvarchar(max);
if @Image IS NULL
Begin Set @txtImage = 'NULL'; END
Else
Begin Set @txtImage = cast(cast(@Image as binary) as nvarchar(max)); END