各位前辈大家好,我刚刚学习c#,遇到一个使用变量进行sql查询的问题。
我定义的表有‘日期’字段,类型为datetime,我要使用变量 selectMonth、minDay、maxDay查询指定时段的数据,但不知道怎么截取字段中的月份和日期。        conStr = "server=(local);user id=sa;pwd=sa;database=forcastserver";
        SqlConnection con = new SqlConnection(conStr);
        con.Open();
        sqlStr = "select * from 积雪 where month(日期)='" + selectMoths + "' and day(日期)>='" + minDay + "' and day(日期)<='" + maxDay + "' order by 流域,日期";
        //sqlStr = "select * from 积雪";查询所有是正常的。
        //SqlCommand myCmd = new SqlCommand(sqlStr, con);
        SqlDataAdapter myDa = new SqlDataAdapter(sqlStr,con);
        DataSet myDs = new DataSet();
        myDa.Fill(myDs);//出错的地方,不知道是不是sql语句有问题,month(日期)这里不对?        if (myDs.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = myDs;
            GridView1.DataBind();
        }
        else
        {
            Response.Write("<script>alert('没有相关记录')</script>");
        }
        con.Close(); 
错误提示:用户代码未被处理 SqlException
')' 附近有语法错误。sql 日期查询语句

解决方案 »

  1.   

    复杂的条件最好使用参数化的sql语句,
      

  2.   

    sqlStr = string.Format(" select * from 积雪 where month(日期)={0} and  day(日期) between {1} and {2} ",Convert.ToInt32(selectMoths),Convert.ToInt32(minDay),Convert.ToInt32(maxDay));
      

  3.   

    sqlStr = "select * from 积雪 where month(日期='" + selectMoths + "' and day(日期>='" + minDay + "' and day(日期)<='" + maxDay + "' order by 流域,日期";
    注;LZ红色右括号是中文,这是不正确的啊,要改为英文状态下的
    sqlStr = "select * from 积雪 where month(日期)='" + selectMoths + "' and day(日期)>='" + minDay + "' and day(日期)<='" + maxDay + "' order by 流域,日期";
      

  4.   

    很显然,从你贴出的SQL语句可以看出,那个右括号明显是中文全角括号,明显和左边的括号不一样哦
      

  5.   

    day(日期的右括号是中文的格式,改成英文形式下的就OK了
      

  6.   

     DATEPART(year,时间字段)=2012年
     DATEPART(month,时间字段)=12月
     DATEPART(day,时间字段)=31日
    select * from table where DATEPART(year,时间字段)=2012
      

  7.   

    参数化的sql查询没学过,看了波西米亚人生的sql语句,学习了。参数化的比较简洁,并且不容易写错,谢谢了。