sql >> Base de Datos >  >> RDS >> PostgreSQL

¿Cómo pasar una tabla o filas a una función en Postgresql?

Una fila está representada por un tipo compuesto, como

CREATE TYPE mytype  AS (
   id integer,
   name text,
   fromdate timestamp with time zone
);

Puede usar un tipo de este tipo como argumento de función.

Para cada tabla de PostgreSQL, existe automáticamente un tipo con el mismo nombre y columnas:

CREATE TABLE mytable (
   id integer PRIMARY KEY,
   name text,
   fromdate timestamp with time zone NOT NULL
);

Entonces puedes crear una función que tome una matriz de este tipo como argumento:

CREATE OR REPLACE FUNCTION myfunc(arg mytable[]) RETURNS void
   LANGUAGE plpgsql IMMUTABLE STRICT AS
$$DECLARE
   t mytable;
BEGIN
   FOREACH t IN ARRAY arg LOOP
      RAISE NOTICE 'id = %', t.id;
   END LOOP;
END;$$;

Puede llamarlo así (asumiendo que hay dos filas en mytable ):

SELECT myfunc(array_agg(mytable)) FROM mytable;
NOTICE:  id = 1
NOTICE:  id = 2
┌────────┐
│ myfunc │
├────────┤
│        │
└────────┘
(1 row)

Alternativamente, puede crear una función que tome un cursor como argumento:

CREATE OR REPLACE FUNCTION myfunc(arg refcursor) RETURNS void
   LANGUAGE plpgsql IMMUTABLE STRICT AS
$$DECLARE
   t mytable;
BEGIN
   LOOP
      FETCH NEXT FROM arg INTO t;
      EXIT WHEN NOT FOUND;
      RAISE NOTICE 'id = %', t.id;
   END LOOP;
END;$$;

Esto se puede llamar en una transacción de la siguiente manera:

BEGIN;
DECLARE c CURSOR FOR SELECT * FROM mytable;
SELECT myfunc('c');

NOTICE:  id = 1
NOTICE:  id = 2
┌────────┐
│ myfunc │
├────────┤
│        │
└────────┘
(1 row)

COMMIT;