'00'附近语法不正确

时间:2011-08-09 18:00:48

标签: c# asp.net

我是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();

2 个答案:

答案 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 ...

周围的单引号