简体   繁体   中英

postgresql - loop doesn't work properly

I wrote function to update or insert into log table some information. Every query should return around 100 records, but below function always updating or inserting only last row.
I thing that I should put RETURN NEXT before END LOOP but it is not working.

CREATE OR REPLACE FUNCTION plugins.update_log()
  RETURNS void AS
$BODY$
DECLARE
    rec record;
BEGIN
FOR rec IN 
    SELECT     na1_nr::integer,
               CASE WHEN c.record_status_id::integer = 8 THEN c.niezainteresowany_powod::text ELSE ots.name::text END reason
    FROM       temp_id c
    LEFT JOIN  plugins.outbounds_telcom_statuses ots ON (ots.telcom_status_id::integer=c.telcom_status_id::integer AND ots.outbound_id::integer = 33)

    LOOP

        UPDATE  plugins.boss_release_log 
        SET     count = count::integer +1 
        WHERE   na1_nr::integer = rec.na1_nr::integer
        AND     reason::text = rec.reason::text;

        IF found THEN
            RETURN;
        END IF;

        BEGIN
            INSERT INTO plugins.boss_release_log(na1_nr,reason,count) 
            VALUES (rec.na1_nr, rec.reason, 1);
            RETURN;
        EXCEPTION WHEN unique_violation THEN

        END;

    END LOOP;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION plugins.update_log()
  OWNER TO ss0;

Move your RETURN statement to the end of your function. Your function MUST have a RETURN statement in it, but when it is hit it exits (for set-returning functions you use RETURN NEXT but that is not applicable here).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM