在Asp.net中的SQL查询按钮上单击事件 [英] Sql Query in Asp.net On button Click Event

查看:68
本文介绍了在Asp.net中的SQL查询按钮上单击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Data.SqlClient.SqlException: Operand data type varchar is invalid for sum operator.


代码在这里


And Code is Here

con.Open();
string col = "select SUM(Price) from Purchase where CustomerName = '"+DropDownList1.SelectedItem.Text+"' ";
SqlCommand cmd = new SqlCommand(col,con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{

TextBox5.Text = dr[0].ToString();
}
con.Close();
}

推荐答案

您表中的价格"列是文本数据类型(varchar,nvarchar,text)吗?您无法将varchar求和.
SUM只能与数字列一起使用.空值将被忽略.
要在SQL中使用SUM(*)函数,您将必须使用数字数据类型,例如int,decimal,money.

您可以在每次需要对其求和或进行其他数学运算时进行强制转换,但是使用适当的数据类型要好得多.将价格列的数据类型更改为数字数据类型.货币或小数可能是一个不错的选择.
Your column "Price" in your table is a text datatype (varchar, nvarchar, text)? You can''t SUM a varchar.
SUM can be used with numeric columns only. Null values are ignored.
To use the SUM(*) function in SQL you will have to use a numeric datatype like int, decimal, money.

You could cast this every time you need to sum it or do other mathematically operations, but it''s a lot better to use a proper datatype. Change the datatype of your Price column to a numeric datatype. Money or decimal would probably be a good choice.


您的价格列是无法累加的varchar列,请使用以下内容:
Your Price column is a varchar column which cannot be summed, use the following:
string col = "select SUM(CAST( Price AS decimal(3,0)) from Purchase where CustomerName = '"+DropDownList1.SelectedItem.Text+"' ";


这篇关于在Asp.net中的SQL查询按钮上单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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