SoFunction
Updated on 2025-04-08

Simple implementation of postgresql loop function

I won't say much nonsense, let's just read the code~

create or replace function aa1(a1 integer[],a2 bigint) returns 
void AS $$
declare ii integer;
declare num integer;
 begin
 II:=1;
 num = 1;
 FOR ii IN 1..a2 LOOP 
 UPDATE student SET
  id=a1[num]
 WHERE cd_id = ii;
 num = num +1;
 if (num>6) then
 num = 1;
 end if;
 end loop;
 end;
$$ LANGUAGE plpgsql;
 
select aa1(array[1,4,5,6,7,8],6742)

Supplement: Summary of stored procedures and loops of postgreSql library in database

Stored procedure templates in postgreSql library

CREATE OR REPLACE FUNCTION p_fx_*** ( OUT v_row INTEGER, OUT v_rote varchar(50), OUT v_log varchar(50))
AS $$
DECLARE
BEGIN
 
 select count(*) into v_row from *The name of the insert table*;
 v_rote := 'SUCCESS';
 v_log := 'SUCCESS';
 
END
$$
LANGUAGE plpgsql VOLATILE

A template written circularly in the postgreSql library, taking the SQL in actual development as an example

Single-layer loop

do $$
declare ***:=***;
begin
  while *** loop
  end loop;
end $$;

declare -- declare variables. If you declare variables, don't forget to add a semicolon;

Double-layer cycle

do $$
declare ***:=***;
begin
  while *Cyclic conditions* loop
    for i in 1..12 loop
    raise notice '%',*Variable name*;
    end loop;
  end loop;
end $$;

raise notice '%', variable name; this is the output statement similar to print in Java.

Put the loop into the stored procedure

CREATE OR REPLACE FUNCTION p_fx_*** ( OUT v_row INTEGER, OUT v_rote varchar(50), OUT v_log varchar(50))
AS $$
DECLARE
BEGIN
 
while *Cyclic conditions* loop
    for i in 1..12 loop
    raise notice '%',*Variable name*;
    end loop;
  end loop;
 
 select count(*) into v_row from *The name of the insert table*;
 v_rote := 'SUCCESS';
 v_log := 'SUCCESS';
END
$$
LANGUAGE plpgsql VOLATILE

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.