SQL for fetching all date/times on a single date - sql

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?

Related

Subquery Excel VBA SQL

I need help with subquery in excel VBA. First: I need look for data by date -> for example from: 20.8.2018 to 21.8.2019 and Second: I need look for data by time from first result - > for example from 08:00:00 to 14:00:00
Now, I am looking data only by Date
strQueryQ7DrRightElox = "Select nio,checked FROM q7_dr_right_elox_incoming_inspection where date >= '" & sDateFrom & "' AND date <= '" & sDateTo & "' "
I found solution . I have two columns Date and Time in SQL DB.Then I created another column datetime where is date and time together in one column and I can compare data correctly

MSACCESS 2010 VBA; Syntax Error in date in query expression

I am creating a simple database for tracking working hours. The idea is that:
Every day you need to input only the days that employee did not work (startDate, endDate, absenceType),
Then calculate working days for the whole month or selected period.
Calculation of working days should take into account weekends (saturday, sunday) and holidays from Holiday table.
I took a function sample from MSDN (Counting the Number of Working Days in Access 2007) and put it into a module in my MS Access 2010 db but each time I run a query I have this error.
Typically the same error appears attempting to run a query in another sample database from somewhere.
The problem is in the strWhere clause:
strWhere = "[Holiday] >=#" & startDate & "# AND [Holiday] <=#" & endDate & "#"
' Count the number of holidays.
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays
The error msg from both databases is available in the link below
Runtime Error 3075 Syntax error in date in query expression
Any help is appreciated.
You must force a format on the string expressions for your dates. Get used to use the ISO sequence yyyy-mm-dd as it works everywhere:
strHolidays = "NameOfYourTable"
strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
' Count the number of holidays.
nHolidays = DCount("*", strHolidays, strWhere)
In the past I have had issues where VBA doesn't always respect the regional date settings. Try forcing it into US format before concatenating it
strWhere = "[Holiday] >=#" & Format(startDate, "MM/dd/yyyy") & "# AND [Holiday] <=#" & Format(endDate, "MM/dd/yyyy") & "#"
Make sure the date is in MM/DD/YYYY order in VBA. Always. I generally use:
strWhere = "[Holiday] >= " & Format(startDate,"\#mm\/dd\/yyyy\#")
the second argument of DCount is strHolidays. That does not look like the name of a table/query. This argument should be the name of a table/query.

retrieve access records that fall between user specified dates

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.

Date value returning in a different format on the first of each month

This question is related to this one, however I thought I'd create a new post since it's not the exact same issue, and the ideas on it were just being repeated.
I have a selection formula for my Crystal Report. It's supposed to select data where the Stage field in one table is 6, and the PaymentDate field in another is less than, or equal to, the value of the DateTimePicker control.
The code that I have below is working fine for most of the dates. However, say for example I have the following data in the database:
Sales_Headers.Stage = 6
Sales_Lines.PaymentDate = 28/01/2017 (January 28th, 2017)
When choosing a date of January 26th, up to January 31st, the data is only retrieved when the date is 28th or higher. However, if I then select a date of 1st February (Or the 1st of any month to be precise), it is returning the date as 02/01/2017, or, 2nd January 2017, so the data isn't shown.
Why is it changing for only the 1st of each month? All other dates are being read correctly, as dd/MM/yyyy, but on the first, it's using the MM portion as the dd portion.
I've tried:
Dim dateTo As Date = dtpCRTo.Value.AddDays(1).Date
dateTo = Format(dateTo, "dd/MM/yyyy")
If cmbCRSupplier.Value = "" Then
selectionFormula = "{Sales_Headers.Stage} = '6' AND {Sales_Lines.PaymentDate} < #" & dateTo & "#"
Then I tried this in the form_Load event, as well as in the Value_Changed event of the DateTimePicker:
Dim dateFormat As String
dt.Format = DateTimePickerFormat.Custom
dt.CustomFormat = "dd/MM/yyyy"
dateFormat = dt.Text
The final thing I tried was just to have no formatting code, and just using:
If cmbCRSupplier.Value = "" Then
selectionformula = "{Sales_Headers.Stage} = '6' AND {Sales_Lines.PaymentDate} <= #" & dtpCRTo.Value.Date & "#"
But it was the same result for all of them.
As well as the method #Siva was talking about (Always a good way, that way you can create the formula there and use the syntax that it's looking for), there is the way you're trying, to do it in VB.NET.
As I just mentioned, the syntax is important, and this is what is causing your issue.
I've not seen anyone try to use DateTimes in this method before, using `#value#.
The correct way to format dates into a RecordSelectionFormula (again, this is something you'll have seen if you'd have created it in Crystal itself), is to DATE(yyyy, MM, dd).
So, the correct way to syntax this is to use:
selectionFormula = "{Sales_Headers.Stage} = '6' AND {Sales_Lines.PaymentDate} <= DATE(" & _
dtpCRTo.Value.Date.Year & "," & dtpCRTo.Value.Date.Month & "," & dtpCRTo.Value.Date.Day & ")"
Use this method to insert your dates into selection formulas in the future, that way you can't get it wrong.
If this doesn't work, then you need to check your Region and Local Date/Time settings in Control Panel, to ensure they're set correctly.

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()"