2017-03-11 32 views
0

在我的代碼少於,然後等於日期不起作用。基於服務的數據庫SQL Select語句的日期不起作用

在DATEBASE DUEDATE字段被選擇作爲日期類型不日期時間

sqlString = "Select [VehiNo], [DueDate], [Works] From [Daily] Where [DueDate] <= '" + today.ToShortDateString() + "' and [ServiceDate] Is NULL"; 
MessageBox.Show(sqlString); 

using (SqlCommand cmd = new SqlCommand(sqlString, conn)) 
{ 
    cmd.CommandType = CommandType.Text; 
    SqlDataReader reader = cmd.ExecuteReader(); 
    dtDue.Load(reader); 
} 
if (dtDue.Rows.Count > 0) 
{ 
    dataListOverDue.DataSource = dtDue; 
    dataListOverDue.Columns["VehiNo"].HeaderText = "Vehicle No"; 
} 

Database Table

Data Loaded in WinForm

我有3個數據網格視圖和3 SQL statment每個查找今天的到期,由於間今天和未來15天,並且已經過期。

我嘗試了很多東西,但都沒有工作,我不知道爲什麼。 我已經嘗試過這樣的參數。

string sqlString = "Select [VehiNo], [DueDate], [Works] From [Daily] Where [DueDate]='@today' and [ServiceDate] Is NULL"; 
cmd.Parameters.AddWithValue("@today", today.ToString()); 

sqlString = string.Format("Select [VehiNo], [DueDate], [Works] From [Daily] Where [DueDate] Between '@today' And '@next'"); 
cmd.Parameters.AddWithValue("@today", today.ToString()); 
cmd.Parameters.AddWithValue("@next", next.ToString()); 

選擇與=返回任何

與選擇之間提供了轉換失敗,< =錯誤

選擇返回在圖像顯示我的所有日​​期。

+0

如果列是datetime類型,那麼爲什麼不使用參數化查詢。格式化日期時間值將不再需要。 –

+0

@ChetanRanpariya我已經試過了,請檢查我的編輯。 –

+0

通過下面發佈的解決方案。 –

回答

0

問題出在您生成查詢並向其添加參數的方式。

您不需要在單引號內包裝查詢參數。如果列和參數的數據類型匹配,則也不需要轉換參數值ToString()。

請通過以下解決方案。

string sqlString = "Select [VehiNo], [DueDate], [Works] From [Daily] Where [DueDate] = @today and [ServiceDate] Is NULL"; 

var sqlCommand = new SqlCommand(); 
sqlCommand.CommandText = sqlString; 
sqlCommand.Parameters.Add("@today", SqlDbType.DateTime); 
sqlCommand.Parameters["@today"].Value = today; 

var next = today.AddDays(20); 
sqlString = string.Format("Select [VehiNo], [DueDate], [Works] From [Daily] Where [DueDate] Between @today And @next"); 
sqlCommand.Parameters.Add("@today", SqlDbType.DateTime); 
sqlCommand.Parameters["@today"].Value = today; 
sqlCommand.Parameters.Add("@next", SqlDbType.DateTime); 
sqlCommand.Parameters["@next"].Value = next; 

這應該可以解決您的問題。

+0

我來到相同的解決方案小時,但謝謝。你能幫我解決另一個問題嗎?由於這個網站很難理解和網站說不說謝謝。所以我在這裏給你發我的其他問題鏈接。即使我不知道這種詢問你的方法是否正確。 http://stackoverflow.com/questions/42587017/how-to-move-cursor-into-maskedtextbox-c-sharp-winforms –

0

嘗試以下

string sqlFormattedDate = today.ToString("yyyy-MM-dd HH:mm:ss.fff"); 

DateTime myDateTime = DateTime.Now; 
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss"); 

,並使用sqlFormattedDate

不要使用字符串連接,使用參數化查詢。傳入DateTime類型的參數值。這避免了格式化問題,提高了後續查詢的性能,並避免了以這種方式構建SQL時所面臨的固有漏洞(SQL注入)。

"where @dateTime <= DateTimeField" 
相關問題