Reputation: 177
Hi i am trying to create a function which loops from 1 to 12 and then use that loop value to calculate a date here is my code so far for the loop which is where the problem is.
FOR i IN 1..12 LOOP
r.duedate := alert_start_period + interval 'i month';
RAISE NOTICE 'Month % gives date of %', i, r.duedate;
END LOOP;
I know the problem is how i am referencing the value i. How do i correctly reference i from the loop so the interval is correct please.
The Error being thrown is
ERROR: invalid input syntax for type interval: "i month"
Upvotes: 0
Views: 59
Reputation: 324285
You can't substitute a var into a string like that. Without using dynamic SQL, the cleanest way is a multiplier:
r.duedate := alert_start_period + i * INTERVAL '1' MONTH;
However, this whole idea is ugly. The loop is unnecessary. Use:
generate_series(alert_start_period, alert_start_period + INTERVAL '12' MONTH, INTERVAL '1' MONTH)
to generate the intervals. If you must, you can loop over that, but I generally find that everything not requiring exception handling is better done as normal set operations rather than pl/pgsql loops.
Upvotes: 3