I have following seed input data:
Thats just example how company payroll goes.
Now,
Would the following not work?
DECLARE @StartDate DATETIME
SELECT @StartDate = '2016-05-01 00:00:00.000'
DECLARE @EndDate DATETIME
SELECT @EndDate = '2017-04-01 00:00:00.000'
DECLARE @Dates TABLE(StartDate DATETIME, EndDate DATETIME)
WHILE @StartDate <= @EndDate
BEGIN
INSERT INTO @Dates (StartDate, EndDate)
SELECT @StartDate - 13, @StartDate WHERE DATEPART(WEEK, @StartDate) % 2 = 1 AND DATEPART(WEEKDAY, @StartDate) = 7
SET @StartDate = @StartDate + 1
END
-- Check the dates here... should be every 2 weeks
SELECT * FROM @Dates
You need some modulo operations and DATEDIFF.
declare @periodStart datetime
declare @periodEnd datetime
set @periodStart = CAST('2011-12-03' as datetime)
set @periodEnd = CAST('2011-12-16' as datetime)
declare @anyDate datetime
set @anyDate = CAST('2011-12-30' as datetime)
declare @periodLength int
set @periodLength = DATEDIFF(day, @periodStart, @periodEnd) + 1
declare @daysFromFirstPeriod int
set @daysFromFirstPeriod = DATEDIFF(day, @periodStart, @anyDate)
declare @daysIntoPeriod int
set @daysIntoPeriod = @daysFromFirstPeriod % @periodLength
select @periodLength as periodLength, @daysFromFirstPeriod as daysFromFirstPeriod, @daysIntoPeriod as daysIntoPeriod
select DATEADD(day, -@daysIntoPeriod, @anyDate) as currentPeriodStart, DATEADD(day, @periodLength -@daysIntoPeriod, @anyDate) as currentPeriodEnd
Gives output
periodLength daysFromFirstPeriod daysIntoPeriod
14 27 13
and
currentPeriodStart currentPeriodEnd
2011-12-17 00:00:00.000 2011-12-31 00:00:00.000