vr552
vr552

Reputation: 301

How to get the same date of the previous month?

What I have tried:

for i in 1..5 loop
  v_input_date := ADD_MONTHS(v_input_date, -1);
end loop;

Results:

29.03.2021.
28.02.2021.
31.01.2021.
31.12.2020.
30.11.2020.

Expected results:

29.03.2021.
28.02.2021.
29.01.2021.
29.12.2020.
29.11.2020.

I could extract the day returned, compare it to the original, and decrease it if needed, but is there a better way how to achieve this?

Upvotes: 1

Views: 291

Answers (1)

Littlefoot
Littlefoot

Reputation: 142743

Code you posted actually doesn't do what you described.

SQL> declare
  2    v_input_date date := date '2021-04-29';
  3  begin
  4    for i in 1 .. 5 loop
  5      dbms_output.put_line(add_months(v_input_date, -1 * i));
  6    end loop;
  7  end;
  8  /
29.03.2021
28.02.2021
29.01.2021
29.12.2020
29.11.2020

PL/SQL procedure successfully completed.

SQL>

Upvotes: 1

Related Questions