简体   繁体   中英

Why does access return inconsistent results when searching between dates?

So I have a little piece of software my work is running to help with receiving and inventory ATM. I made a report to pull item entries between Date A and B. I use the MonthCalendar Control and then pull the date range using the .SelectionStart and .SelectionEnd properties of the control, as the user will typically select a week ( mon-fri ) for reporting.

Heres the SQL I send to my Access DB:

InvDB.GetQuery("
  SELECT
    [_Date],Commodity,Gross,Net,Description
  FROM
    Tags
  WHERE
    Format([_Date],'yyyy') = '" + DateTime.Now.Year.ToString() + "' AND
    Format([_Date],'m/d/yyyy') Between #" + monthCalendar1.SelectionStart.ToString("M/dd/yyyy") + "# AND #" + monthCalendar1.SelectionEnd.ToString("M/dd/yyyy") + "# 
    AND NOT Category = 'Finished Goods' 
    ORDER BY [_Date] Asc",
"Tags");

Dates are stored in this format: "9/1/2015 10:31:50 AM"

I was never able to get the in SQL date functions working initially so I had to resort to this method, which I am sadly aware is greatly inefficient...

First the reason why I went with the Year comparison, is because when I was selection a date range, access was returning all years associated with the dates. Not only the one that the properties returned. ( I also know this will cause issues if dealing between years of course )

And finally the reason why I ask the question here, is that when the user selects the dates, and tries to get the items between the dates... The returned selection, is so random... I've never seen the type of obscure results this SQL returns... I can't even see a pattern to it. I select one week, and it only gives 3 of the 5 days out of that week along with the first two weeks of the previous month... Another week selection is accurate... Another yet, gives 2 of the 5 days of that week...

Edit - Based on the suggestion below, I now push query through with parameters. I also removed the SQL Format() after testing still yielded the same randomness. This simple query so far, is returning accurate information.

SELECT
  [_Date],Commodity,Gross,Net,Description
FROM
  Tags
WHERE
  [_Date] Between ? AND ?
  AND NOT Category = 'Finished Goods' 
ORDER BY 
  [_Date] Asc

Try not to convert the [_Date] to string. You wouldn't be able to use the BETWEEN correctly for date when you convert it.

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