各位前辈大家好,我刚刚学习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 日期查询语句
我定义的表有‘日期’字段,类型为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 日期查询语句
注;LZ红色右括号是中文,这是不正确的啊,要改为英文状态下的
sqlStr = "select * from 积雪 where month(日期)='" + selectMoths + "' and day(日期)>='" + minDay + "' and day(日期)<='" + maxDay + "' order by 流域,日期";
DATEPART(month,时间字段)=12月
DATEPART(day,时间字段)=31日
select * from table where DATEPART(year,时间字段)=2012