2013-04-26 19 views
0

我得到了一個錯誤,當我做了如下:錯誤的SQL查詢與日期時間

DateFrom具有爲datetime

enter image description here

數據類型,我的C#代碼:

string strQuery = "Select * FROM Agenda Where DateFrom='" + Calendar1.SelectedDate.Date.Date + "' "; 
SqlCommand command = new SqlCommand(strQuery, Global.myConn); 
da = new SqlDataAdapter(command); 
da.Fill(Global.dsAgenda, "Tabel"); 
ddlActivity.DataSource = Global.dtAgenda; 
ddlActivity.DataBind(); 

CALENDAR1類型:

enter image description here

錯誤:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

+1

使用的SqlParameter – realnumber3012 2013-04-26 07:48:47

+0

格式是什麼'Calendar1.SelectedDate.Date.Date'在?打印出來並檢查。它試圖將它投射到一個日期(比較)和失敗。請說明什麼樣的數據庫和版本。 SQL Server? – 2013-04-26 07:49:36

+0

@ realnumber3012你如何做到這一點? – 2013-04-26 07:57:07

回答

4

你應該更喜歡使用parameters

string strQuery = "SELECT * FROM Agenda WHERE DateFrom = @Date"; 
SqlCommand command = new SqlCommand(strQuery, Global.myConn); 
command.Parameters.Add("@Date", SqlDbType.DateTime).Value = Calendar1.SelectedDate; 
+0

Ownage;)謝謝 – 2013-04-26 08:02:51

1

使用此

Convert(DateTime,Calendar1.SelectedDate.Date.Date,103) 
+0

我使用這個:Convert.ToDateTime(Calendar1.SelectedDate.Date.Date) 將varchar數據類型轉換爲日期時間數據類型導致超出範圍的值。 – 2013-04-26 07:55:39