[英]Error: Conversion failed when converting datetime from character string .NET SQL Server
I realise this question has been asked before, but after going through the previously answered questions, i still can't quite figure out what's wrong with this code. 我知道之前曾有人问过这个问题,但是经过前面回答的问题之后,我仍然不太明白这段代码有什么问题。
FYI I am in the UK. 仅供参考,我在英国。
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();
}
}
On Error is you cannot pass column name as parameter 出现错误时,您无法将列名作为参数传递
"SELECT * FROM " + schemaName + "." + viewName + "
WHERE @dateFieldName BETWEEN @startDate AND @endDate";
this should be 这应该是
"SELECT * FROM " + schemaName + "." + viewName + "
WHERE " + dateFieldName + " BETWEEN @startDate AND @endDate";
To avoid sqlInjection attack make use of Sp_executeSQL
to execute this type of query, because this is dynamic sql query. 为了避免sqlInjection攻击,请使用
Sp_executeSQL
来执行这种类型的查询,因为这是动态sql查询。
It will depend on your SQL Server locale settings, but perhaps 这将取决于您的SQL Server语言环境设置,但也许
string dateFormat = "dd-MMM-yyyy HH:mm:ss";
will work for you? 会为你工作吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.