Go to Top

Querying SQL Server DateTime Fields in Access

The other day I was troubleshooting a query in Access that was using a SQL Server table and coming up short on the number of records retrieved. I knew I was supposed to get x records and instead was getting y. (First rule in designing queries is to always know the answer before you start building it, otherwise, how are you going to validate your query?).  One of my criteria fields was DateCreated, a datetime field in SQL Server. For some reason I wasn’t getting all of the records back for the date period specified.

Time Paradox
I finally nailed down what it was: when you use a date criteria, i.e.: between StartDate and EndDate you may not get back all of the records since all dates are stored with a time stamp.

ADVERTISING
ACCESS SAFETY AND TRAINING DATABASE

In my case I was using a default value of getdate() on the field in my table. Getdate() will insert the date and time the record was committed, for example 4/11/2011 2:32:73 PM. I was aware of this behavior and the issues it causes with queries but had forgotten about it when I came across my problem.

Append Dawn and Midnight to your criteria
To capture all of the data I had to modify my criteria to include times, for example:

Between #4/1/2011 00:00:00 AM# And 4/30/2011 11:59:59 PM#

I was using a form where the user enters the start and ending dates for the analysis, so I had my code append the times:

strCriteria = “Between #” & txtStartDate & ” 00:00:00 AM# And #” & txtEndDate & ” 11:59:59 PM#”

But what if Access (or the user) enters the date?
When the user enters a date in the field or when Access does it via code there is no issue, the record is saved with 00:00:00 as the time portion and you can use dates with no time stamps to query the data.

 

 

About Juan Soto

Juan Soto is a Senior Access Developer at IT Impact Inc. and a Microsoft Access MVP. He specializes in Access with SQL Server databases. His passion for Access has led him to helping a wide range of businesses in helping them establish a secure, stable and efficient environment with SQL Server. He's a frequent speaker at Access user groups nationwide and recently spoke at the Orange County SQL Saturday # 73. If you wish to have Juan speak at your next group meeting you can contact him here.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Contact Us
[gravityform id="16" title="false" description="false"]