compare date/time via VBA with date/time in Access DB - sql

How to compare a date/time via VBA with a date/time in an Access DB?
The query I use
adoRS.Open "SELECT * FROM currentpositions WHERE ((currentpositions.
[dateLT])=" & "#" & date_from_message & "#" & ")", adoConn, adOpenStatic,
adLockOptimistic
I only achieve to compare a date.
Anybody an idea?
Regards
Camastanta

adoRS.Open "SELECT * FROM currentpositions WHERE DateValue(currentpositions.
[dateLT]) = DateValue(" & "#" & date_from_message & "#)", adoConn, adOpenStatic,
adLockOptimistic
See, if the above helps.
DateValue extracts the date part from a given date/time. So, it can be used to compare date, ignoring the time part.

IMHO you should never build your SQL statements using string concatenation. Instead use parameterized SQL queries. This will save you from problems like the one you are facing with date/time comparison.

Does your system have dates in either yyyy-mm-dd or dd-mm-yyyy format? If so see Return Dates in US #mm/dd/yyyy# format to convert your dates in mm-dd-yyyy so Access can work with them properly.

Related

MS Access SQL "INSERT INTO" statement produces date in wrong format despite correct regional setting

My computer's regional date setting is dd/mm/yyyy. I am using MS Access. I would like to insert records into a database using the SQL INSERT INTO statement. When I try to insert a date using the #dd/mm/yyyy# syntax, and view the resulting record in the table after, it turns out the record displays the date in the format mm/dd/yyyy instead, but ONLY for the first 10 days of the month; if the day is 11 onwards, the record displays dd/mm/yyyy as intended.
For example if in SQL code I input #09/02/2022#, the table will display the record with the date 02/09/2022 instead. However if my SQL code is#11/02/2022#, then the correct order 11/02/2022 is shown in the record.
Please help.
Ok, the way this works?
You don't have to care, know, or think about the users regional format settings.
So, if you drop some control on a form? Just make sure that control is set to a date type format. Your done.
BUT ONE big whopper:
IN ANY AND ALL cases, your string based date format MUST be in USA format. Or you can use ISO date format.
dim MyDate as Date
MyDate = me.InvoiceDate
So, now we have a internal format date variable. How to insert into a table?
dim strSQL as string
strSQL = "INSERT INTO tblInvoice (InvoiceNum, InvoiceDate, InvoiceAmount " & _
"VALUES (1234, " & quDate(MyDate) & ",50)"
So, you ALWAYS format the date value into USA format.
You can type that format command over and over, but that fast becomes tiring.
so, I use a little helper function:
Public Function quDate(dt As Date) As String
quDate = "#" & Format(dt, "mm\/dd\/yyyy") & "#"
End Function
Public Function quDateT(dt As Date) As String
' return formatted date with time
quDateT = "#" & Format(dt, "mm\/dd\/yyyy HH:NN:SS") & "#"
End Function
So, you don't have to care about the date and regional format, but for a in-line SQL insert command that you build in code? Yes, you MUST convert to USA format of mm/dd/yyyy.
So, you can display dates in any format. For forms, for reports - not a problem.
However, the ONLY exception here is your code that builds a insert statement. That date string format must be #mm/dd/yyyy#.
Or, ISO:
#yyyy-mm-dd#
So, either format is fine, but it is a hard and fast rule that you must conform to.
So, from a text box on a form, if not data bound, then you want to ensure that the text box is set as a date type text box (fomrat date).
then in code:
dim strSQL as string
strSQL = "INSERT INTO tblFun (BirthDate) " & _
"VALUES (#" & format(txtDate,"mm/dd/yyyy") & "#)"
currentdb.Execute strSQL
Or, if you have that helper function, then this:
strSQL = "INSERT INTO tblFun (BirthDate) " & _
"VALUES (" & qudate(txtDate) & ")"

SQL DATEDIFF Function returns wrong values

Im executing following sql statement to get the sum values using date difference as a condition. "t_QueryDemand" is the table name and "DESIRED_SHIP_DATE" is the value I compare with current system date. But, I always get a date difference higher than 44100, even though the actual difference is between 0-60. DESIRED_SHIP_DATE data type is datetime2(7). I'm using MS SQL server database. What could be the issue.
Dim curDate As Date = Date.Today()
Dim strSql7DayDemand As date= "SELECT SUM(ORDER_QTY) AS ORDQTY, (TOTAL_SHIPPED_QTY) AS SHIPQTY, DATEDIFF(day," & curDate & ",DESIRED_SHIP_DATE),DESIRED_SHIP_DATE as DIFF from t_QueryDemand where ID='" & Trim(txtPartID.Text) & "' AND DATEDIFF(DAY," & curDate & ",DESIRED_SHIP_DATE) >" &
Instead of using a injection use the SQL function GETDATE()
DATEDIFF(day,GETDATE(),DESIRED_SHIP_DATE)
This will calculate the date on the server instead of locally like you are currently doing.
As has been pointed out you have a serious security vulnerability -- you need to use parameterized queries and not string concatenation or you are vulnerable to an SQL injection attack.
It will also make your code more robust -- right now you have txtPartID.Text and you are just putting that into your query but what if someone enters an non-number in this field -- you have no way of catching that now. With a parameterized query of a numeric type you would catch this problem when you converted the data entry to a number.

strSQL between date range excel VBA

I am trying to run an strSQL within Excel VBA between two date ranges.
See below part of my code relevant to this:
Dim DateMin As String
Dim DateMax As String
DateMin = Format$(Sheets("Setup").Range("c5").Value, "mm/dd/yyyy")
DateMax = Format$(Sheets("Setup").Range("c6").Value, "mm/dd/yyyy")
strSQL = "SELECT [COSTCENTRE_CODE],[PROJECT_CODE],[HOME_VALUE],[CT_DEADLINE] FROM [AA_CST_CENTRE_TRANSACTION_SIMPLE_VIEW] where [CT_DEADLINE] between #" & DateMin & "# AND #" & DateMax & "#"
When I run this I get an "incorrect syntax nea '#'" error. The format of cells C5 + C6 are in the same mm/dd/yyyy format - am using the American date format as believe SQL only uses American dates? I have tried adjusting the dates but no luck.
When I run "debug.print strsql" I get the below:
SELECT [COSTCENTRE_CODE],[PROJECT_CODE],[HOME_VALUE],[CT_DEADLINE] FROM [AA_CST_CENTRE_TRANSACTION_SIMPLE_VIEW] where [CT_DEADLINE] between #02/01/2020# AND #03/31/2020#
I have tried removing the # around the dates and I no longer get the error, however no data shows at all - there is definitely data there for these dates.
Anyone have any ideas as believe this is an SQL issue rather than an Excel VBA issue?
Does running this SQL work? SELECT [COSTCENTRE_CODE],[PROJECT_CODE],[HOME_VALUE],[CT_DEADLINE] FROM [AA_CST_CENTRE_TRANSACTION_SIMPLE_VIEW] just to make sure the issue is in the date part and not before. If this is not running then the issue is in this part and not in the date part.
And I believe SQL is using YYYY-MM-DD hh:mm:ss.sss as date format. Check that out if you have done the first suggested test and this query runs.
And as far as I know only Access accepts # but in SQL-Server you would neet to use ' instead (which should also work for Access).
Also note that
BETWEEN '02/01/2020' AND '03/31/2020'
is actually:
BETWEEN '02/01/2020 00:00:00.000' AND '03/31/2020 00:00:00.000'
So notice that you are missing anything that happened after 12am on 03/31/2020.

What's wrong with my SELECT statement?

I'm using this code to get the last number in a column where date of column is today date:
cn.Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\bysys.mdb")
rs.Open("Select max(snum) From tblbill where idate = #" & Format(Today.Date, "dd/MM/yyyy") & "# ", cn, 1, 2)
If IsDBNull(Rs.Fields(0).Value) Then
TextBox6.Text = 1
Else
TextBox6.Text = Rs.Fields(0).Value + 1
End If
Sometimes it works correctly, but sometimes, it always return 1..
When you submit a value which can represent a valid date in mm/dd/yyyy format, Access will interpret it as such. You could deliberately format it as mm/dd/yyyy instead of dd/mm/yyyy. But many of us prefer yyyy/mm/dd because Access always interprets that format correctly and we humans needn't be bothered about possible confusion over whether the date is dd/mm/yyyy or mm/dd/yyyy format.
"Select max(snum) From tblbill where idate = #" & Format(Today.Date, "yyyy/mm/dd") & "# "
However the db engine supports a function, Date(), which your query can use to refer to the current date without bothering about any formatting. So this alternative seems simplest to me ...
"Select max(snum) From tblbill where idate = Date()"

Date comparision with access database in VB.NET

I am stuck with a query to compare the current date with date stored in access database table in the given format 7/25/2012
I am using this query:
Sql = "SELECT max(token_today)
FROM token
WHERE issue_date = #" & FormatDateTime(Now, DateFormat.ShortDate) & "#"
and I am getting the error below:
conversion from string ** to type 'Integer' is not valid.
Please tell me how to compare the date.
Thank You!
If you wish to compare today's date, there is no need for an external reference:
Sql = "SELECT max(token_today) FROM token WHERE issue_date = Date()"
This saves all sorts of problems with locale, as well.
i think this should work:
"SELECT max(token_today) FROM token WHERE issue_date = #" & FormatDateTime(Now,"YYYY/MM/DD") & "#"