Is it possible to have multiple secondary use of a returning value in a CTE statement in Postgres?

StackOverflow https://stackoverflow.com/questions/22786726

Question

I want to insert my foreign keys in multiple tables after a insert into the main table in one CTE. I can't find the solution so it may well be impossible...

see this example:

CREATE TABLE test_main (main_id serial NOT NULL, main_name character varying(64) default null);
CREATE TABLE test_sub_one (sub_one_id serial NOT NULL,sub_one_main_id integer NOT NULL,sub_one_name character varying(64) default null);
CREATE TABLE test_sub_two (sub_two_id serial NOT NULL,sub_two_main_id integer NOT NULL,sub_two_name character varying(64) default null);

WITH main as (
    INSERT INTO test_main (main_name) VALUES ('test1') RETURNING main_id
) 
INSERT INTO test_sub_one (sub_one_main_id,sub_one_name) SELECT main_id, 'testsub1' FROM main,
INSERT INTO test_sub_two (sub_two_main_id,sub_two_name) SELECT main_id, 'testsub2' FROM main;
Était-ce utile?

La solution

Use another CTE for the second insert:

WITH main as (
    INSERT INTO test_main (main_name) VALUES ('test1') RETURNING main_id
), sub1 as (
  INSERT INTO test_sub_one (sub_one_main_id,sub_one_name) 
  SELECT main_id, 'testsub1' FROM main
)
INSERT INTO test_sub_two (sub_two_main_id,sub_two_name) 
SELECT main_id, 'testsub2' FROM main;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top