If I want to save the primary key (mytable_id
) from a single insert I've done the following:
CREATE OR REPLACE FUNCTION myfunct(ownerid text) RETURNS void AS
$$
DECLARE myvar INTEGER;
BEGIN
INSERT INTO mytable (long_description) VALUE 'testing';
SELECT CURRVAL('mytable_mytable_id_seq') INTO myvar;
END;
$$
LANGUAGE plpgsql;
The problem is, I now want to do the same BUT on multiple inserts. I want to insert a row, and take that newly inserted row's PK and use it as a foreign key in another insert.
So I have
DECLARE myvar2 INTEGER;
INSERT INTO mytable (long_description)
SELECT DISTINCT type FROM schema1.myothertable WHERE type IS NOT NULL;
INSERT INTO mytable2 (foreign_key1, foregin_key2)
VALUES (myvar, myvar2); -- somewhere pk from mytable is stored in myvar2
Is there a way to perform these two inserts in the same query?
I wanted to avoid loops but I'm not sure this can be done without it.