2011-11-02 171 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

乾杯,猜測比真的晚,永遠不會,大聲笑.. –