SQL Server Getting error: failed to convert parameter value from a String to a DateTime

xqkwcwgp  于 2023-02-18  发布在  其他
关注(0)|答案(1)|浏览(184)

I get this error:
Failed to convert parameter value from a String to a DateTime.

The error occurs at ExecuteDataset(Connection, cmd, query, parameters);

Code:

int paramCount = 2 + results.Count;

SqlParameter[] sqlParam = new SqlParameter[2];
sqlParam[0] = new SqlParameter("@FROMDATE", SqlDbType.DateTime);
sqlParam[0].Value = Convert.ToDateTime(SearchRequest.FromDate).ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
results.Add(sqlParam[0]);

sqlParam[1] = new SqlParameter("@TODATE", SqlDbType.DateTime);
sqlParam[1].Value = Convert.ToDateTime(SearchRequest.ToDate).ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
results.Add(sqlParam[1]);
                        
foreach (var o in strCode)
{
    SqlParameter paramRef = new SqlParameter();
    paramRef.ParameterName = "@Param" + results.Count;
    paramRef.Value = o;
    results.Add(paramRef);

    lstParam.Add(paramRef.ParameterName);
}
                        
SqlParameter[] sqlParams = new SqlParameter[paramCount];
sqlParams = results.ToArray();

string Query;
Query = "select StudID,StudName from StudentDetails  
         where CourseCode in ({2}) and Coursedate between @FROMDATE and @TODATE";

var inClause = String.Join(",", lstParam);
Query =  Query.Replace("{2}", inClause);
vyswwuz2

vyswwuz21#

Issue is resolved, I was passing incorrect date format... During debugging DATE do read it as e.g 20130831 which I changed it to 2013-08-31 format and it worked for me...

相关问题