r/SQL • u/Glum-Molasses-4181 • May 07 '26
SQL Server SQL2018 - variable date ranges
Hi - I need help with a variable date range formula. I need to capture data from Jun 1 of the previous year through May 31 of current year. The query needs to be able to run anytime through the year and needs to work in future years. So this year it would be 6/1/25 -5/31/26, but next year would be 6/1/26-5/31/27. I can't figure how without hardcoding the dates. I found a formula but it only works with earlier versions of sql. Can anyone assist?
0
Upvotes
4
u/Glum-Molasses-4181 May 07 '26
Thanks so much for your replies! After reading the links and responses, this was the solution:
@startdate = datefromparts(datepart(yyyy,getdate())-1,6,1)
@enddate = datefromparts(datepart(yyyy,getdate()),5,31).
This will give me June 1 of the previous year to May 31 of current year no matter what year it runs in.
4
u/SQLDevDBA May 07 '26 edited May 07 '26
You need a date table that has Fiscal Year logic specific to your company.
Using it, you’ll be able to query by fiscal year and get the correct dates.
That’s how I learned working for a certain Cartoon mouse many years ago and still use it today.
How to Create one, by Aaron Bertrand: https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/
Performance issues to look out for, by Brent Ozar: https://www.brentozar.com/archive/2020/08/date-tables-are-great-for-users-but-not-so-great-for-performance/