Bucles en PosgreSQL – For y While

Ejemplo de For

CREATE OR REPLACE FUNCTION ventas_stg.mi_for(n INTEGER DEFAULT 10) 
RETURNS VOID AS $$
DECLARE
    rec RECORD;
BEGIN
    FOR rec IN SELECT product_code 
        FROM ventas_stg.vw_product_stg 
        ORDER BY product_code
        LIMIT n 
    LOOP 
         RAISE NOTICE 'Valor extraido: %', rec.product_code;
    END LOOP;
    
END;
$$ LANGUAGE plpgsql;

SELECT ventas_stg.mi_for(3) ;

Ejemplo de While

create or replace function sp_imprimir_variable()
 returns void as $$
 declare k int;
 begin
   k = 0;
   while k <= 100 loop
     RAISE NOTICE 'Procesando - % ', k;
     k = k + 10;
   end loop;
 end;
 $$ language plpgsql;