我是asp& amp;的新手sql server。我在SQL查询中有问题。
string obal ;
decimal _obalss = 0;
decimal obalss = 0;
sconnection c = new sconnection();
string cus_id = Session["cusid"].ToString();
DateTime maxdate = DateTime.Parse(fromdt.Text, new System.Globalization.CultureInfo("en-US"));
string mdate = maxdate.ToString();
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
SqlDataReader dr = c.reader(query_sl);
if (dr.Read())
{
decimal.TryParse(dr["amount"].ToString(), out _obalss);
obalss = _obalss;
}
else
{
obalss = 0;
}
dr.Close();
dr.Dispose();
答案 0 :(得分:11)
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
maxdate
是一个日期,您必须将其放在单引号中。更好的是应该使用参数化SQL查询,否则您很容易受到SQL注入攻击。这样的事情怎么样:
string query_sl = "select sum(amount) as amount from sale where cusid = @CUSID and invdate < @MAXDATE group by cusid";
using(SqlCommand cmd = new SqlCommand(query_sl, c))
{
cmd.Parameters.Add(new SqlParameter("@CUSID", SqlDbType.Int)).Value = cus_id;
cmd.Parameters.Add(new SqlParameter("@MAXDATE", SqlDbType.DateTime)).Value = maxdate;
...
}
答案 1 :(得分:1)
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < '" + maxdate + "' group by cusid";
请注意maxdate ...
周围的单引号