Search code examples
c#sqldatetimems-accessoledb

Access Data type mismatch of date in sql query


I am trying to get a list of orders from my access database that were ordered between 2 dates. this is my query:

"SELECT * FROM Orders WHERE OrderDate >= '#" + DateTime.Parse(txtDate.Text) + "#' AND OrderDate <= '#" + DateTime.Parse(txtEndDate.Text) + "#'";

the 2 textboxes recieve the dates directly from 2 ajax calendar extenders. i have already made sure that the first date is before the second, and i had made sure that the data inserted to the database was also inserted like '#"+date+"#', but i "still data type mismatch in query expression". can anyone try and identify a problem with my query?


Solution

  • Assuming you have data like this:

    var txtDate = new { Text = "2020-08-01" };
    var txtEndDate = new { Text = "2020-08-01" };
    

    your query might look like this:

    var fromDate = DateTime.ParseExact(txtDate.Text, "yyyy-MM-dd",
                                     CultureInfo.InvariantCulture).ToString("yyyMMdd");
    
    var toDate = DateTime.ParseExact(txtEndDate.Text, "yyyy-MM-dd",
                                 CultureInfo.InvariantCulture).ToString("yyyMMdd");
    
    var query =
        $"SELECT * FROM Orders WHERE OrderDate>='{fromDate}' AND OrderDate<='{toDate}'";
    

    or the last part can be:

    var query =
        $"SELECT * FROM Orders WHERE OrderDate BETWEEN '{fromDate}' AND '{toDate}'";