将数据类型nvarchar转换为十进制时出错。 [英] Error converting data type nvarchar to decimal.

查看:98
本文介绍了将数据类型nvarchar转换为十进制时出错。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用存储过程并在asp.net上调用它。我收到此错误将数据类型nvarchar转换为十进制时出错。有一个表格调用艺术,其中我有参数:

I am using stored procedure and calling it on asp.net.I am getting this error "Error converting data type nvarchar to decimal." there is table call art in which i have parameter as:

create procedure arts(
@name varchar(50),
@description varchar(50),
@Price decimal(10,2)
)
as
   begin
       insert into arts(name,description,Price) values(@name,@description,@Price)
   end



我将其称为:


and I am calling it as:

SqlCommand cmd=new SqlCommand("spInsertArts",con);
cmd.CommandType=System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@name",txtname.Text);
cmd.Parameters.AddWithValue("@description",txtdesc.Text);
cmd.Parameters.AddWithValue("@Price",txtprice.Text);
con.Open();
cmd.ExecuteNonQuery();





当我执行它时,它会给我以上异常。请帮助



When I execute it,it is giving me above exception.please help

推荐答案

那是因为价格十进制在存储过程中输入,但是你要传递 string value。

That is because Price is decimal type in Stored Procedure, but you are passing string value.
cmd.Parameters.AddWithValue("@Price",txtprice.Text);



参考答案在准备好的声明中使用SqlDBType.Decimal C# [ ^ ]知道如何传递十进制值。


Refer answer Using SqlDBType.Decimal in Prepared Statement C#[^] to know how to pass decimal value.


您需要使用正确的类型设置参数值。尝试下面的十进制参数与 AddWithValue 方法

you need to set the parameter values with correct type. try below for Decimal parameter with AddWithValue method
decimal yourValue = Convert.ToDecimal(txtprice.Text);
cmd.Parameters.AddWithValue("@Price",yourValue);





另请注意,您的存储过程名称是 arts ,但在您的代码中,您输入为 spInsertArts ,确保您在数据库中给出了正确的存储过程名称



SqlCommand cmd = new SqlCommand(spInsertArts ,con);



Also note that your stored procedure name is arts but in your code you put as spInsertArts, make sure that you have given correct stored procedure name as in database

SqlCommand cmd=new SqlCommand("spInsertArts",con);


嗨试试这个。在这段代码中,首先我们检查它是否为int。



A.如果是int,我们将其转换为十进制,

B 。否则我们可以传递null或者可以显示任何警告信息。





int number;

string yourVale = txtprice.Text;



bool result = int.TryParse(yourValue,out number);



if(result)

{

cmd.Parameters.AddWithValue(@ Price,Convert.ToDecimal(yourValue));

} < br $> b $ b其他

{

cmd.Parameters.AddWithValue(@ Price,null); //或者你可以显示任何警告信息。



}
Hi try this. In this code, first we check is it int or not.

A. if it is int we convert it in decimal,
B. else we can pass null or can show any warning message.


int number;
string yourVale = txtprice.Text;

bool result = int.TryParse(yourValue, out number);

if (result)
{
cmd.Parameters.AddWithValue("@Price", Convert.ToDecimal(yourValue));
}
else
{
cmd.Parameters.AddWithValue("@Price", null); // or you can show any warning message.

}


这篇关于将数据类型nvarchar转换为十进制时出错。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆