I'm migrating old reporting systems to a modern Java code base and stumbled upon Microsoft Sql Server stored procedure that generated table with dates (Year, Period, WeekStarting, WeekEnding). I need to migrate this code into Java and make it dynamic, as opposed to generate it a table and take up space in the DB.
Seeking a help from a Sql Server expert to help me understand how those dates are derived, and especially numbers in the Period
column
USE [Reporting]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GenDataforPeriodsTable]
@enddate VARCHAR(10)
AS
DECLARE @startdate VARCHAR(10)
BEGIN
SET NOCOUNT ON;
SELECT @startdate = DATEADD(DAY, 1, MAX(WeekEnding)) FROM Periods;
WITH CTE_DatesTable
AS
(
SELECT CAST(@startdate as date) AS tempdate
UNION ALL
SELECT DATEADD(dd, 1, tempdate)
FROM CTE_DatesTable
WHERE DATEADD(dd, 1, tempdate) <= @enddate
)
INSERT INTO Periods (YEAR, Period, WeekStarting, WeekEnding)
SELECT YEAR(tempdate) as Year, MONTH(DATEADD(DAY, -3, tempdate)) as Period,
DATEADD(DAY, -6, tempdate) as WeekStarting, tempdate as WeekEnding
FROM CTE_DatesTable
WHERE DATENAME(weekday, tempdate) = 'SUNDAY'
OPTION (MAXRECURSION 0)
END
GO
it generates table like this: