I have a client who reports on 13 27 day periods in the financial year and I am trying to work out some dynamic SQL to identify what reporting period an invoice was raised in.
This is what I have so far but the while loop is crashing after the first loop.
IF OBJECT_ID('#Periods', 'U') IS NOT NULL
drop table #Periods
create table #Periods
([start_date] date, [end_date] date, Period varchar(3) )
declare @LYdt datetime,
@CYdt datetime,
@Period int
SET @Period = 0
SET @LYdt = '09/01/2016'
SET @CYdt = '09/01/2017'
While @Period <=13
insert #Periods
select
[Start_Date] = dateadd(mm,datediff(mm,'',@LYdt),'') - datepart(dw,dateadd(mm,datediff(mm,'',@LYdt),'')+0)+ 22,
[End Date] = (dateadd(mm,datediff(mm,'',@LYdt),'') - datepart(dw,dateadd(mm,datediff(mm,'',@LYdt),'')+0)+ 22)+27,
[Period] = 'P'+ convert(varchar(2),@Period)
SET @Period = @Period + 1
SET @LYdt = dateadd(d,27,@LYdt)
SET @CYdt = dateadd(d,27,@CYdt)
Can anyone assist with where I have gone wrong please?
Dave
addiditonal: sample result set of sql will look like this: