How to Find Start and End Dates of All Weeks Between Two Dates in SQL Server?
In this article, I will give you information on how to find the start and end dates of all the weeks between two dates in SQL Server.
Let me tell you from the beginning, the following query works based on the week start date you have determined.
If you set the week start day to Tuesday, it shows the start and end dates based on Tuesday.
You can easily do this by adapting the code below.
DECLARE @StartDate DATETIME = '2021.10.04'; --I chose Monday as the week start date. DECLARE @EndDate DATETIME = '2021.10.31'; WITH CTE AS (SELECT @StartDate WeekStartDate, DATEADD(wk, DATEDIFF(wk, 0, @StartDate), 6) WeekEndDate UNION ALL SELECT DATEADD(ww, 1, WeekStartDate), DATEADD(ww, 1, WeekEndDate) FROM CTE WHERE DATEADD(ww, 1, WeekEndDate) <= @EndDate) SELECT * FROM CTE;
When you run the code, you will see a result similar to the one below.
As you can see, it showed us the start and end dates between the two specified dates.
Good luck to everyone in business and life.