2021-10-28

Why does my week of the year's query show "2022.52" when it should show "2021.52"

I have a query that gave me all the 12 following weeks :

      insert #T_period_futur
               (TPF_year,
                TPF_period_number,
                TPF_start_period,
                TPF_end_period
               )
         select year(dateadd(month, @period_number * +1-1, @next_end_month)),
          convert(varchar(4), case when datepart(ISO_WEEK, dateadd(week, @period_number * +1, @next_sunday)) < 53
                                      then year(dateadd(week, @period_number * +1, @next_sunday))
                                      else year(dateadd(week, @period_number * +1, @next_sunday)) - 1
                                    end) 
                + '.' + right('00' + convert(varchar(4), datepart(ISO_WEEK, dateadd(week, @period_number -1, @next_sunday))), 2),
               dateadd(week, @period_number * +1, dateadd(day, (datepart(weekday, @today)-1) * -1 - 7+1, @today)),
             dateadd(week, @period_number -1, DATEADD(wk, DATEDIFF(wk,0,GETDATE()), 6))
               ;

I call it inside a while loop that does this :

while @period_number <= @nb_period
begin 

 --The previous query..
   select @period_number = @period_number + 1;

end;

With @period_number = 1 and @nb_period = 12

But the result isn't the one expected as you can see :

enter image description here

The weeks 51 and 52 are supposed to be in the year 2021 and not the 2022.

Expected results :

enter image description here

What am I doing wrong?



from Recent Questions - Stack Overflow https://ift.tt/3BnyEJI
https://ift.tt/3bg4gq2

No comments:

Post a Comment