retrieve access records that fall between user specified dates - sql

The table has a date field that is text. The SQL statement is:
"SELECT datefield, anotherfield FROM tablename WHERE CDate(datefield) BETWEEN #" & dateStart & "# AND #" & dateEnd & "#"
dateStart and dateEnd are strings, like "10/02/2017" and "10/4/2017". I used CDate to convert the string datefield to a date, and the bracketing # around the start and end date strings so that they will be treated as date. I have tried, literally, dozens of different variants of the WHERE clause with no luck. Any suggestions are appreciated.

I certainly agree that dates should not be stored as text. However, if you are stuck with the table design then you will need to use CDate for all three of your "date" fields:
SELECT CDate([datefield]) AS myDate, anotherfield
FROM Table2
WHERE (((CDate([datefield])) Between CDate([dateStart]) And CDate([dateEnd])));

I've also used your ways in storing and retrieving date in mySQL. However, I only used one field instead of your perspective dateStart and dateEnd. I would suggest you only create one field for storing date. Here's how I managed to catch the values between those dates using VB.NET.
SELECT datefield, anotherfield FROM tablename WHERE datestoredfield BETWEEN '" & selectedDateFrom.toString("MM/dd/yyyy") & "' AND '" & selectedDateTo.toString("MM/dd/yyyy") & "';
I've indicated .toString("MM/dd/yyyy") at the end of the selected dates its because your current stored date format in your date field is MM/dd/yyyy.

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 for fetching all date/times on a single date

I have a table of whose rows contain a date/time filled with appointment times. The appointment times are a single field (i.e. the date and the time together). I've created a recordset to fetch all the appointments which occur on a given date:
Dim dt as date
dt = #3/2/2019#
Set rs = Currentdb.OpenRecordSet("SELECT stuff FROM Appt WHERE
Int(Appt.apptTime) = #" & dt & "#") --------
This works, but the "Int" function makes it inefficient. One solution would be to separate the date/time field into two fields (date and time) then just search on the date field. Unfortunately, I don't have the option of modifying the database structure.
Does anyone have a suggestion of how I can make this fetch more efficient?
You must format the date expressions properly and remember the equal option:
Set rs = Currentdb.OpenRecordSet("SELECT stuff FROM Appt WHERE Appt.apptTime >= #" & Format(dt, "yyyy\/mm\/dd") & "# AND Appt.apptTime < #" & Format(DateAdd("d", 1, dt), "yyyy\/mm\/dd") & "#")
I just figured out a solution:
WHERE (Appt.apptTime > #" & dt & "#) AND (Appt.apptTime < #" & dt + 1 & "#")
You can use DateValue(Appt.apptTime)
eg:
"WHERE ( DateVaue(Appt.apptTime) = #" & dt & "#"
The above will return only the date part and remove the time portion.
However, the above can't use high-speed indexing. So, your follow answer of :
WHERE (Appt.apptTime > #" & dt & "#) AND (Appt.apptTime < #" & dt + 1 & "#")
will run much faster. The only other issue is that you should (need) to force the format to USA format, else your posted solution can fail depending on the users reginal (date format) settings. So, on some computer you find the above will not work, or fail, or even get things like 4/5/2020 mixed up. Is that April 5, or May 4th?
So, you need to correctly format the date to USA and ensure that you IGNORE the users date format, else your code will fail on many computers with different date formats.
You should create a helper function for this, like this:
Public Function quDateT(dt As Date) As String
' return formatted date
quDateT = "#" & Format(dt, "mm\/dd\/yyyy HH:NN:SS") & "#"
End Function
Then, your query becomes:
WHERE (Appt.apptTime > " & qudateT(dt) & ") AND (attt.apptTime < " & qudateT(dt + 1)
Now in your case, DT will not have time, so the time portion of qudateT will be 00:00:00.
So, your example follow up should work, but you want to FORCE the date format to MM/DD/YYYY (USA) format, and if users have their setting such as DD/MM/YYYY, then your example query will fail on computers with such (different) regional settings.
I don't see why date formatting matter as all dates, regardless of displayed format, are stored as double-precision, floating-point numbers. The integer portion being the number of days since December 30, 1899; the fractional portion being the fraction of the 24-hour day. So my computation (in my updated "found a solution" post), which treats the dates as numbers should be immune to whatever date format has been chosen for the display of dates, right?

Does putting a date format on a date field make a difference in vba?

I've been looking and how people write code and was wondering if placing a format on a date field makes a difference. For example I saw this Format(EndDate, "mm/dd/yyyy") in a query but EndDate is defined as a Date field in the Table.
What are the benefits and problems that may arise for doing this?
strEDate = "#" & Format(EndDate, "mm/dd/yyyy") & "#"
strHSurg = "SELECT TOP 1 [Health Surcharge]FROM tblTax WHERE [Effective Date] <= strEDate " ORDER BY [Effective Date] DESC;"
If EndDate is a Date field couldn't you have the query like this
strHSurg = "SELECT TOP 1 [Health Surcharge]FROM tblTax WHERE [Effective Date] <= " & EDate & " ORDER BY [Effective Date] DESC;"
Does it matter? Or is it done so if the database is moved to a computer with the dd/mm/yyyy format the formulas will not be affected?
Format takes a Date variable/field and converts it to String. The difference between the two is far more than visuals. You cannot perform date type functions (like DateAdd) on a String or String functions (like Replace) on a Date.
I generally use the Format function when I am adding the date to a string. That can be a string the user will see (for example in a report header you can have different outputs like "Total Sales for 1/1/2020" or "Total Sales for January 1, 2020") or when generating an SQL query string to make sure the expected date format is what Access expects and avoid localization issues.
In every case the data is kept as a Date data type. I never store date data as String.
I like to format my dates using VBA because you never know what the formatting of a field may be. If there is a specific date format on the field you are writing to then the field format overrides the format assigned by VBA. Just like typing in the field. You can enter the data in any format, the field formatting will coalesce the data in to it's stated format.
To be safe, use the same format in VBA that you would expect the field to have.

Can't filter MS access datetime field using short date

I am trying to generate a crystal report for my program, apparently I wasn't able to filter those data which is in datetime format if i use "=" and not "> or <".
my code goes something like this
dim x as string ="1/1/2014"
dim y as date
y=cdate(x)
select from [tblname] WHERE [datetime field]=#" & y &"#
the query won't yield any record assuming there is more than one record with 1/1/2014 date not unless i copy the actual datetime data stored in access or use the "> or <"
is there any way that i can format in my SQL query the datetime field to short date for easy comparison? because i believe the time stored is the reason why i can't filter it using "="
This would be better as a parameter query. But since I don't know how or if you can use an Access parameter query with Crystal Reports, I'll suggest you format the date value as #yyyy-m-d#.
"select from [tblname] WHERE [datetime field]=" & Format(y, "\#yyyy-m-d\#")
If you want to ignore time of day when matching [datetime field] to day y, you can use DateValue([datetime field]) which gives you midnight of that date.
"select from [tblname] WHERE DateValue([datetime field])=" & Format(y, "\#yyyy-m-d\#")
However, if your table contains many rows, you don't want to evaluate DateValue for every row. Instead you can do something like this, and it can utilize indexed retrieval for faster performance if [datetime field] is indexed.
"select from [tblname] WHERE [datetime field]>=" & Format(y, "\#yyyy-m-d\#") & " AND [datetime field]<" & Format(y + 1, "\#yyyy-m-d\#")

Error converting data type varchar to datetime using GETDATE()

I realise this is quite a common problem banded around forums, but I am at a loss as to what I've done wrong here.
I have a 'Current' table something like:
ID(uniqueidentifier)
Name(nvarchar max)
FileName(nvarchar max)
FileVersion(smallint)
CurrentVersionDate(datetime)
The CurrentVersionDate is entered using the GETDATE() function within SQLserver.
When a user hit's 'Create file' on my website, the details of this table are transferred to a 'History' Table. So I use a stored procedure to select * details from 'Current' and save each value as a variable (i'm using vb.net in a visual studio project). I'll show the date variable as this is the problem. I'm saving this as a 'date' variable:
Dim dDate as Date
dDate = dr("CurrentVersionDate")
Then I send these variables to another stored procedure to enter into the 'History' table:
Execute sp_InsertHistory '" & ID & "','" & strName& "','" & strFile & "','" & intVersion & "','" & dDate & "'"
I declare the date variable in the stored procedure as:
#Date datetime,
with the insert statement:
INSERT INTO History
(ID, Name, FileName, FileVersion, VersionDate)
VALUES
(#ID, #Name, #FileName, #FileVersion, #Date)
The 'History' table has the same setup as the 'Current' table. Stepping through the code, this error is caught:
Error converting data type varchar to datetime
Surely the variables isn't varchar? And even if it is, the string is surely in the correct format for SQLserver because I'm just selecting the date value SQL has given!
Any thoughts?
Since you are putting the date between quotes, is a varchar '" & dDate & "'", but I think the problem you have with the conversion could be that you are retrieving the date in your local format and you have to insert the date in the SQL Server in his own format.
Try inserting the date as a string in this format: dDate.ToString("MM/dd/yyyy HH:mm:ss")
the string is surely in the correct format for SQLserver
How do you know that? To be safe, I'd use string in unambiguous format: YYYY-MM-DDTHH:MM:SS, e.g. 2013-05-13T01:01:00.