2011-11-02 129 views
0
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查询

+3

使用参数,它的确比格式化日期更好... – Marco

+1

@sikender:我想你的意思是说'你需要指定你得到什么样的错误。 – jgauffin

回答

0

我认为这将解决您的问题:

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()); 
0

试试这个:

DateTime dt = DateTime.Now.AddDays(day - 1); 
SqlCommand cc = new SqlCommand(
    "SELECT COUNT(*) FROM Appointment_Info WHERE [email protected]", cn); 
cc.Parameters.AddWithValue("@dt", dt); 
2

什么你以后是这样而不是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对象的做法。

+0

k感谢它非常有用 – user966602

+0

干杯,猜测比真的晚,永远不会,大声笑.. –