I have this table:
| Key_No | Import_Date |
|---|---|
| 12345678 | 2023-09-01 |
| 98765432 | 2023-10-01 |
| 85231654 | 2023-11-01 |
| 00020102 | 2023-12-01 |
I want to find the data of import_date after this month.
I tried a SQL statement like this:
select *
from Table1
where DATEPART(mm, Import_date) = MONTH(GETDATE())
and DATEPART(yyyy, import_date) = YEAR(GETDATE())
But I can only find the data for October. I need to show all data after the current month.
In my opinion, two things are important here:
EOMONTHwhich returns the last day of the current month.WHEREclause. They will be called for every single row of the table and will likely slow down the query, escpecially when the table has many rows. We will do better to just declare a variable with the date. Then we check if the date from the table is later than this date or not. Thus, a function is executed once only and not a thousand times or even a million times.So if the current month should not be included and we want to start with the first day of the next month, we can do this:
If also the current month should be included, this will do:
Try out with some sample data here
I recommend to read this documentation that explains both the function
EOMONTHand how to use a variable.