Reputation: 351
I got a very strange problem.
When I filter my data in the current year everything is working fine:
But If I try to go back a year, suddenly I get a blank report...
Going to the next year isn't a problem, like you can see here:
My code is:
These 2 values come through as a 'date' in a private sub
datumvan = DateTimePickerVan.Value.ToLocalTime
datumtot = DateTimePickerTot.Value.ToLocalTime
Dim culture As New CultureInfo("pt-BR")
sqlstr = "SELECT * FROM [Geschiedenis$] WHERE Aangemeld BETWEEN '" & datumvan.ToString("d", culture) & "' AND '" & datumtot.ToString("d", culture) & "'"
See also how the sql looks like if it goes to the debugging:
So to conclude: everything is working fine unless I go to the previous year. If I place: NOT BETWEEN, everything is reversed, and I see all the data.
I tried to replace BETWEEN with >= and <= as well, but the same thing occurred.
Any ideas?
Upvotes: 0
Views: 330
Reputation: 94914
Aangemeld is obviously a date, as it should be. So you must compare Aangemeld with dates. In order to do so,
datumvan.ToString("dd/MM/yyyy")
How to convert a string to a date in SQL depends on the DBMS you are using. Here are some examples:
MySQL:
" ... WHERE Aangemeld BETWEEN STR_TO_DATE('" & datumvan.ToString("dd/MM/yyyy") & "','%d/%m/%Y') AND ... "
SQL_Server:
" ... WHERE Aangemeld BETWEEN CONVERT(datetime,'" & datumvan.ToString("dd/MM/yyyy") & "',103) AND ... "
Oracle:
" ... WHERE Aangemeld BETWEEN TO_DATE('" & datumvan.ToString("dd/MM/yyyy") & "','dd/mm/yyyy') AND ... "
Many DBMS (such as MySQL, SQL-Server, and PostgreSQL) also accept a string in ISO format as as date literal.
" ... WHERE Aangemeld BETWEEN '" & datumvan.ToString("yyyyMMdd") & "' AND ... "
In Oracle such a literal must be preceded by DATE:
" ... WHERE Aangemeld BETWEEN DATE'" & datumvan.ToString("yyyyMMdd") & "' AND ... "
One more thing: I don't know if this is the case in other DBMS, too, but I know that Oracle treats a date without time as a date at midnight, as it only knows datetime data type. So a between clause would exclude the last day. Which is why in Oracle you would compare TRUNC(Aangemeld) instead of Aangemeld.
Upvotes: 1