Subquery Excel VBA SQL - 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

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?

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.

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