我意識到這個問題之前已經問過,但在經歷了以前回答的問題之後,我仍然無法弄清楚這段代碼有什麼問題。錯誤:從字符串轉換日期時間時轉換失敗.NET SQL Server
僅供參考我是在英國。
public static void GetDataForCSEP(string viewName, string schemaName,
string dateFieldName, DateTime startDate, DateTime endDate)
{
string dateFormat = "yyyy/MM/dd HH:mm:ss";
//Connect to SQl Server
string commandText = "SELECT * FROM " + schemaName + "." + viewName + " WHERE @dateFieldName BETWEEN @startDate AND @endDate";
using (SqlCommand sqlCmd = new SqlCommand(commandText,sql_Conn))
{
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.Add("@dateFieldName",SqlDbType.NVarChar, 30).Value = dateFieldName;
sqlCmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = DateTime.Parse(startDate.ToString(dateFormat));
sqlCmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = DateTime.Parse(startDate.ToString(dateFormat));
sql_Conn.Open();
sqlCmd.ExecuteNonQuery();
}
}
爲什麼你在做'DateTime.Parse(startDate.ToString(dateFormat))''''startDate'已經是DateTime值。爲什麼將其轉換爲字符串只是爲了將其轉換回來? –
因爲我是垃圾程序員:) – MrBliz