查询日期时间
本文关键字:时间 日期 查询 | 更新日期: 2023-09-27 18:13:30
string date = DateTime.Now.AddDays(day - 1).ToShortDateString().ToString();
string count = "select count(*) from Appointment_Info where APPT_Dt=''" +
Convert.ToDateTime(date) + "'' ";
SqlCommand cc = new SqlCommand(count, cn);
int appoinments = Convert.ToInt16( cc.ExecuteScalar().ToString());
上面的查询不工作,请看到并告诉他们有什么问题吗?
您需要的是这样的SQL:
DateTime dtFrom = DateTime.Now.AddDays(day - 1).Date;
DateTime dtTo = past.AddDays(1);
string strSQL = "Select Count(*) From Appointment_Info Where APPT_Dt Between @from And @to";
int appoinments = 0;
using (SqlCommand cc = new SqlCommand(strSQL, cn))
{
cc.Parameters.AddWithValue("@from", dtFrom);
cc.Parameters.AddWithValue("@to", dtTo);
appoinments = Int32.Parse(cc.ExecuteScalar().ToString());
}
问题是你不需要精确的日期,因为它不会给你任何东西,你更需要范围日期,意思是在过去的日期和它的第二天之间的任何东西。
上面的代码还提供了使用参数和正确处理Command对象的更好实践。
我想这会解决你的问题:
string date = DateTime.Now.AddDays(day - 1).ToShortDateString().ToString();
string count = "select count(*) from Appointment_Info where convert(int,convert(varchar, APPT_Dt,112))=convert(int,convert(varchar, @date,112)) ";
SqlCommand cc = new SqlCommand(count, cn);
cc.parameters.AddWithValue("@date",date);
int appoinments = Convert.ToInt16( cc.ExecuteScalar().ToString());
试试这个:
DateTime dt = DateTime.Now.AddDays(day - 1);
SqlCommand cc = new SqlCommand(
"SELECT COUNT(*) FROM Appointment_Info WHERE APPT_Dt=@dt", cn);
cc.Parameters.AddWithValue("@dt", dt);