Search code examples
postgresqlfunctioncursor

update is not allowed in a non volatile function postgres


I tried to use a cursor with multi parameters, the function was created without any problem, but then when I call my function using

select scratchpad.update_status()

I get the following error:

update is not allowed in a non volatile function

the function:

create  function scrat.update_status() returns void
as
$$
DECLARE
  day_to_process record;

BEGIN
FOR  day_to_process   in  (SELECT distinct inst_status.date,inst_status.code,scrat.inst_status.id
                             FROM scrat.inst_status
                             WHERE inst_status.status ='S'
                             ORDER BY 1)
  LOOP
    raise notice 'Processing Date %', day_to_process.date::text;
   update scrat.inst_status
    set status = (select a.status from
                                  (select status, max(date)
                                FROM scrat.inst_status
                                where status <> 'S'
                                  and date::date < day_to_process.date
                                group by status
                                order by 2 desc
                                limit 1)a)
    where inst_status.date = day_to_process.date
      and id =day_to_process.id
      and code=day_to_process.code;
  END LOOP;
END ;
$$ LANGUAGE plpgsql STABLE;

Solution

  • As the documentation states:

    STABLE indicates that the function cannot modify the database, and that within a single table scan it will consistently return the same result for the same argument values, but that its result could change across SQL statements.

    So you will have to mark the function as VOLATILE.