I am doing my project on ACCESS for the "front" part with the forms, and in SQL Server for the "back-end" part with the databases, everything works fine exect for one thing : I don't understand how to filter Access's forms with SQL Server's date type.
I have looked for everything on the web and all the solutions don't seems to work for my case (maybe because of the ACCESS/SQL Server env), things like :
Me.Form1.Filter = "[date born] = #" & Format("11/04/2022", "dd/mm/yyyy") & "#"
'with VBA directly
SELECT * FROM dbo_Person WHERE [date born] = Format('11/04/2022','dd/mm/yyyy') ;
-- with SQL Request from ACCESS on the table
but everytime I have the same issue: nothing is displayed even if there is rows who have this date in the right column. It is like if no row respected this condition even though it is not the case.
I'm guessing it may be an issue with SQL Server Date type who doesn't convert well on ACCESS.
That is how is desplayed by default in my ACCESS the dates of the column (my ACCESS software is setuped in French btw)
The data is well recognize as "not a String" because when I try to filter with a String an error appears.
Can someone help me to know where I missed something or misstyped something please ?
Edit : the Date column seems actually to be recognized as Short String in ACCESS, it may be the issue but still don't know how to fix because it is indeed a date type on sql server
"Texte court" can be translated to "short text" or short String
First, if you use data type DateTime2 in SQL Server, that will be read as text in Access.
So, change that to DateTime.
Next, use the universal format yyyy-mm-dd when filtering date values:
FilterDate = DateSerial(2022, 4, 11)
Me.Filter = "[date born] = #" & Format(FilterDate, "yyyy\/mm\/dd") & "#"
' Linked table in Access:
Sql = "SELECT * FROM dbo_Person WHERE [date born] = #" & Format(FilterDate, "yyyy\/mm\/dd") & "#;"
Related
I have an SQL statement in VBA that when i run it, it updates my table with incorrect information. I've been struggling with this code for over a week trying workarounds and debugging but to no avail. I've searched online and found nothing even close to this.
DIM SQL as String
DIM periodStart as Date
DIM periodEnd as Date
periodStart = DateSerial(Year(Date), 12, 1)
periodEnd = DateSerial(Year(Date), 12, 15)
MsgBox "Period Start: " & periodStart & " Period End: " & periodEnd
SQL = "UPDATE EmpTime SET EmpTime.beginning = " & periodStart & " & EmpTime.ending = " & periodEnd & ";"
DoCmd.RunSQL SQL
The above code gives me a message box that shows me the periodStart and periodEnd variables are being built properly but then when i look to the table, the information is not the same as the Message box.
MsgBox
Table
Why is this happening and what can I do to fix it/avoid it ?
What I think is happening here is that your SQL is shaking out to be:
UPDATE EmpTime SET EmpTime.beginning = 12/1/2019, EmpTime.ending = 12/15/2019;
Access is not super amazing at guessing your intentions when you just send it math problems like this. Because it doesn't recognize your first date as a properly formatted string (12/01/2019 would be more appropriate) it is making the educated guess that you literally wanted to divide 12 by 1 by 2019. Which results in a decimal, or a very early time of the first date that MS Access can record: 12/30/1899 (like 12:05am, but there is no time dimension in play so it's dropped).
Instead try:
UPDATE EmpTime SET EmpTime.beginning = #" & Format(periodStart, "mm/dd/yyyy") & "# & EmpTime.ending = #" & Format(periodEnd, "mm/dd/yyyy") & "#;"
This does two things:
It formats (using the Format() function) your date into something access will recognize on its own.
It surrounds the date in # which is the microsoft office-y way of saying "This is explicitly a date, treat it as such or throw an error". Which is a much better scenario then "Guess what I meant when I send you this math/date"
Lastly, as Gordon mentions, and I also HIGHLY recommend is to switch this code over to use parameterized inputs in your SQL. here is a good write up of what that looks like. This solves two issues in your current code
Your malformed date would most likely error on being assigned to the correctly typed parameter before the SQL was executed alerting you that you have a bad date. (no guessing what went wrong and no bad data hitting your database)
You are protected from SQL Injection by users of your workbook. I assume this is not a super important facet of your workbook/application though since this is probably an internal company or personal thing and everyone using it can be trusted, but I am always in favor of hardening your code as best as possible since it's just good practice.
SQL = "UPDATE EmpTime SET EmpTime.beginning = #" & periodStart & "#, EmpTime.ending = #" & periodEnd & "#"
I have a problem regarding dates from my program to a stored procedure in SQL.
My program takes a date from the excel spreadsheet and parses it as such:
tempDate = Date.FromOADate(exWS.Cells(exRow, myMatchedColumns(2)).value)
Dim format() = {"dd/MM/yyyy", "dd-MM-yyyy", "yyyy-MM-dd"}
dueDate = Date.ParseExact(tempDate, format,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
Globalization.DateTimeStyles.None)
dueDate is 'DATE' variable so I'm assuming at this point the 'dueDate' is a universal Date object. I think this was the best way to parse BOTH English regional date and Polish dates, since this will be used on a Polish machine.
However, when sending values to my stored procedure:
mySQLString = "EXEC bsp.PartPrice_sp " & _
"'" & dueDate & "', " & _
"'" & myPartID & "', " & _
"'" & currency & "'"
English sends EXEC bsp.PartPrice_sp '01/09/2015', 'L555', 'USD' which returns the price.
Polish sends EXEC bsp.PartPrice_sp '2015-09-01', 'L555', 'USD' which incurs the error:
The conversion of a nvarchar data type to a datetime data type
resulted in an out-of-range value.
I understand the error, but the next execution of the stored procedure, the Polish machine sent 2015-09-10 which returned a price fine. I'm guessing since 2015-10-09 is still within range but interestingly it returned the correct price for 10th September 2015.
Nevertheless I'm struggling to find a universal way of executing the stored procedure in both English and Polish. Any help you can give to parse the dates correctly which also makes SQL happy would be awesome.
Thanks.
Program written in VB .NET.
P.S If I change the #duedate in the stored procedure from nvarchar to datetime, I get an:
Error converting data type varchar to datetime.
Error, which I'm guessing is from the English format. Many thanks.
Date formats in inline non-parameterised queries are one of those things that can drive you spare in my experience.
So -
If at all possible issue a SqlCommand with a collection of SqlParameters, into which you add the actual Date-typed .Net variables. Much safer.
If you really have to keep the inline SQL for some reason, never pass in regionalised date formats. They reliably break for odd reasons. Ideally send the server YYYY-MM-DD hh:mm:ss.ms, but to be safe run that through a centralised function - partly it's easier than making sure you're calling the right .ToString() format in all places correctly, partly I've in the past had occasional servers complain even at that format.
I am working on this Access 2002 database. It uses linked servers to SQL Server 2008. I am having a problem where in load of the main form it does a DLookup and looks at a date.
EndDate = Nz(DLookup("End_Date", "Employee", "EmpID= " & EmpID & " AND End_Date IS NOT NULL AND End_Date < #" & Now & "#"), "")
Now this works fine in Access 2002, but in Access 2010 I get the:
Conversion failed when converting date and/or time from character string
Here's the kicker though, it works in Access 2010 for one user: myself. No other users does it work for and also other installations with Windows 7 and the Access 2010 Runtime work fine. On the same machine the MDB works correctly also. If I replace the Pound signs with single quotes like in SQL Server it runs fine on the 2010 machine but no longer works on 2002 (duh).
It's just been wracking my brain and normally I have been able to get it to work by uninstalling all of Office and then reinstalling and making sure the SP1 for the Access Runtime was installed last.
Instead of transforming the value of Now() to a string in your DLookup, just let the db engine determine Now() for itself.
EndDate = Nz(DLookup("End_Date", "Employee", _
"EmpID= " & EmpID & " AND End_Date IS NOT NULL AND End_Date < Now()"), "")
That approach does not depend on a conversion between Date/Time and string and back again, so will avoid the problem you reported.
If you want to examine how the original DLookup gave different results, try something like this on the different machines:
Dim strCriteria As String
strCriteria = "EmpID= " & EmpID & " AND End_Date IS NOT NULL" & _
" AND End_Date < #" & Now & "#"
Debug.Print "strCriteria: " & strCriteria
EndDate = Nz(DLookup("End_Date", "Employee", strCriteria), "")
After running that code, go to the Immediate window (Crtl+g) and inspect the value of strCriteria.
Note that the type of date / time field that you are using in SQL Server may cause problems, which could explain the difference between versions.
Access 2010 provides limited support for four new date/time data types
that were added in SQL Server 2008:
TIME
DATE
DATETIME2
DATETIMEOFFSET
-- http://office.microsoft.com/en-us/access-help/create-an-access-project-HA010341589.aspx#_Toc257281378
If you are storing the dates in SQL server as the data type “Date” or
“Date2” try changing them to “DateTime” I had this problem linking
data from SQL server 2008R2 to access 97, access did not see it as a
date and treated it like text
-- MS-Access front-end does not recognise dates from SQL Server
As an aside, there is no need for End_Date IS NOT NULL, once you add another criterion, null values will be excluded unless you specifically include them.
I have read a huge pile of problems and solutions, and I just can't figure out what I'm doing wrong.
BounceDate = DateValue(txtBounceDate.Value)
bncSql = "DELETE _BounceMaster.* FROM _BounceMaster" & _
" WHERE _BounceMaster.DateCheck >= #" & BounceDate & "#;"
DoCmd.RunSQL bncSql
_BounceMaster.DateCheck is in Date/Time format, which I think may be the issue, but I can't figure out what different format it should be in, or how to get there. As best as I can tell, BounceDate is correct - even using CDate didn't make a idfference. I have gotten both data mismatch errors, and currently, with code as above, I am getting syntax errors. What am I doing wrong?
I suppose the problem comes from date formatting. The BounceDate variable is DateTime type, so when you concatenate with string type variable, VBA automatically casts DateTime variable into String type using date format from your regional settings.
As I correctly remember, SQL interpreter from MS Access feels comfortable only with mm/dd/yyyy date format, so please try this:
BounceDate = DateValue(txtBounceDate.Value)
bncSql = "DELETE _BounceMaster.* FROM _BounceMaster" & _
" WHERE _BounceMaster.DateCheck >= #" & Format(BounceDate, "mm/dd/yyyy") & "#;"
DoCmd.RunSQL bncSql
It should be
DELETE FROM _BounceMaster
not
DELETE _BounceMaster.* FROM _BounceMaster
You should be using parameterized queries, as your code is subject to SQL injection attack.
I coded something using Date statement in Access VBA. It was working fine until the start of this month, but now I am seeing that the Date has automatically changed the format from dd/mm/yyyy to mm/dd/yyyy. Has anyone else encountered the same problem?
The default Access SQL date format, regardless of locale, is mm/dd/yyyy. If you use an invalid date format, it will 'helpfully' try to convert that to a valid date for you.
So, if you use '30/09/2008', it will recognize you're using dd/mm/yyyy, and convert it appropriately. However, a value like '10/01/2008' is a valid mm/dd/yyyy value to begin with, so it will not be converted, and stored incorrectly in case you actually meant dd/mm/yyyy....
The solution is to always convert your date values to a mm/dd/yyyy string prior to using them in Access SQL statements. You have to be a bit careful here, as using VBA date format masks may not work entirely as you'd expect on non-US locales (e.g. 'helpfully' interpreting "mm/dd/yyyy" as "the localized short date format"), so please test carefully using your particular Access/VBA version.
Access requires a date to be unambiguous. It is generally recommended that you use yyyy/mm/dd, regardless of locale. For example:
strSQL="SELECT SomeDate FROM tblT WHERE SomeDate=#" & Format(DateVar, "yyyy/mm/dd") & "#"
Try this code:
stLinkCriteria = "[ProjectDate] Between #" & Format(CDate(Me![txtDateFrom]), "mm/dd/yyyy") & "# And #" & Format(CDate(Me![txtDateTo]), "mm/dd/yyyy") & "#"
It works for me.
This works:
sentenciaSQL = "UPDATE Numeraciones " & _
"SET Valor = " & Valor & ", " & _
"Fecha = #" & **Format(fecha,"mm/dd/yyyy HH:nn:ss") & "#, " &** _
"Id_Usuario = " & Id_Usuario & _
" WHERE Nombre = '" & Nombre & "'"
I have been very successful using the datevalue() function. When getting dates from unbound controls it seems to be clever enough to interpret the format "dd/mm/yyyy" correctly. Thus, a Jet SQL query like
"Select * from DateTable where StartDate = datevalue(" & me!TxtStartDate & ");"
seems to work every time.
I was experiencing same issue while trying to build a SQL string through VBA.
My locale settings use dd/mm/yyyy and I was trying to put into SQL statement data taken from an unbound textbox in a form.
The issue was due to the fact I was declaring, let's say, varMyDate as "date" type, so the engine reverted the format back even after the format.
Since you are really building a string the logical and proper data type is "string", and that solved the problem.