VBA/ Sql to run query on Month only (1 Viewer)

GUIDO22

Registered User.
Local time
Today, 10:22
Joined
Nov 2, 2003
Messages
515
I wish to use a recordset call with SQL to return all records for the current month/year... can you advise on the parameters to Format to achieve this please..?
 

CJ_London

Super Moderator
Staff member
Local time
Today, 10:22
Joined
Feb 19, 2013
Messages
16,670
in sql the criteria would be something like

WHERE recordDate > (date-day(date)) and recordDate<dateadd('m',1,date-day(date))+1
 

GUIDO22

Registered User.
Local time
Today, 10:22
Joined
Nov 2, 2003
Messages
515
I came up with this ... (Month(Now())=MONTH(SaleDate) AND Year(Now())=YEAR(SaleDate))
 

ebs17

Well-known member
Local time
Today, 11:22
Joined
Feb 7, 2020
Messages
1,983
SQL:
SELECT
   *
FROM
   TableX
WHERE
   DateTimeField >= DateSerial(Year(Date()), Month(Date()), 1)
      AND
   DateTimeField < DateSerial(Year(Date()), Month(Date()) + 1, 1)
This also allows you to use an index that may exist. This works faster - sometimes you need speed.
 

CJ_London

Super Moderator
Staff member
Local time
Today, 10:22
Joined
Feb 19, 2013
Messages
16,670
my suggestion in post #2 also utilises indexing
 

ebs17

Well-known member
Local time
Today, 11:22
Joined
Feb 7, 2020
Messages
1,983
This is correct, because no calculation is applied to the table field and there is no NOT or <> in the comparison.

However, in SQL Date must be used as Date() (=> function). Date without brackets would be interpreted as unknown variable.
 

CJ_London

Super Moderator
Staff member
Local time
Today, 10:22
Joined
Feb 19, 2013
Messages
16,670
hmm verified it in the immediate window - sql will add the () automatically. But agree, poor presentation on my account
 

ebs17

Well-known member
Local time
Today, 11:22
Joined
Feb 7, 2020
Messages
1,983
What you should also pay attention to: A DateTime field can contain time components, which would therefore also have to be taken into account.
Code:
? Date - Day(Date)
31.01.2023
Here, practically the whole day before the current month would be included in the filter.
 

Gasman

Enthusiastic Amateur
Local time
Today, 10:22
Joined
Sep 21, 2011
Messages
14,449
in sql the criteria would be something like

WHERE recordDate > (date-day(date)) and recordDate<dateadd('m',1,date-day(date))+1
I kept getting 'expected expression' for the last criteria when using it in the immediate window?
Changed 'm' to "m" and it worked as I expected?
 

Users who are viewing this thread

Top Bottom