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

¿Puedo usar el valor de retorno de INSERT...RETURNING en otro INSERT?

Puede hacerlo a partir de Postgres 9.1:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val)
SELECT id
FROM rows

Mientras tanto, si solo está interesado en la identificación, puede hacerlo con un disparador:

create function t1_ins_into_t2()
  returns trigger
as $$
begin
  insert into table2 (val) values (new.id);
  return new;
end;
$$ language plpgsql;

create trigger t1_ins_into_t2
  after insert on table1
for each row
execute procedure t1_ins_into_t2();