Domanda

I am creating a stored procedure using plpgsql by passing a type array and do a loop inside the procedure so that I can insert each info type

CREATE TYPE info AS(
    name  varchar,
    email_add  varchar,
    contact_no  varchar 
);

CREATE OR REPLACE FUNCTION insert_info(
    info_array  info[]
) RETURNS varchar AS $$
    DECLARE
        info_element  info;
    BEGIN
        FOREACH info_element IN ARRAY info_array
        LOOP
            INSERT INTO info_table(
                name,
                email_add,
                contact_no
            ) VALUES(
                info_element.name,
                info_element.email_add,
                info_element.contact_no
            );
        END LOOP;
        RETURN 'OK';
    END;
$$ LANGUAGE plpgsql;

The problem is I don't know how to use the function with the array input. I did some experiments (with just some stupid inputs):

SELECT insert_info(
    ARRAY[('Arjay','myEmail@email.com','1234567')]
);

But PostgreSQL says that it is a record[] and I still haven't tested the Loop part ...

I have found a similar problem in this link:
Declare variable of composite type in PostgreSQL using %TYPE
but it did not use arrays. If this is just a duplicate question maybe you guys can point me in the right direction!

È stato utile?

Soluzione

The call would be (with two array elements):

SELECT insert_info('{"(Arjay,myEmail@email.com,1234567)"
                    ,"(Bjay,my2Email@email.com,2234567)"}'::info[]);

Or with ARRAY constructor:

SELECT insert_info((ARRAY['(Arjay,myEmail@email.com,1234567)'
                         ,'(Bjay,my2Email@email.com,2234567)'])::info[]);

Or:

SELECT insert_info( ARRAY['(Arjay,myEmail@email.com,1234567)'::info
                         ,'(Bjay,my2Email@email.com,2234567)']);

But the whole operation can be more efficient with plain SQL using unnest():

INSERT INTO info(name, email_add,contact_no)
SELECT * FROM unnest('{"(Arjay,myEmail@email.com,1234567)"
                     , "(Bjay,my2Email@email.com,2234567)"}'::info[]);

You can wrap it into an SQL function if you need it as function call ...

CREATE OR REPLACE FUNCTION insert_info(info_array info[])
  RETURNS void
  LANGUAGE sql AS
$func$
INSERT INTO info(name, email_add,contact_no)
SELECT * FROM unnest($1)
$func$;

Same call.

Your original function would return after the first array element, btw.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top