简体   繁体   中英

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.

It will depend on your SQL Server locale settings, but perhaps

string dateFormat = "dd-MMM-yyyy HH:mm:ss";

will work for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM