I have a table with a UUID key that is generated on insert. I need to use that key in multiple future inserts and want to store it in a variable.
CREATE TABLE table1 (UUID uuid PRIMARY KEY DEFAULT gen_random_uuid(), blah integer);
CREATE TABLE table2 (UUID uuid PRIMARY KEY DEFAULT gen_random_uuid(), UUID table1Uuid);
INSERT INTO TABLE1 (blah) values (1234);
INSERT INTO TABLE1 (blah) values (6789);
.....
INSERT INTO TABLE2 (table1Uuid theUuidMadeFromInsert1234);
I think I can make sure all the future inserts into TABLE2 are in the same session (maybe the same script) as those for TABLE1. Would like to do something like
uuid1234 = INSERT INTO TABLE1 (blah) values (1234);
uuid6789 = INSERT INTO TABLE1 (blah) values (6789);
.....
INSERT INTO TABLE2 (table1Uuid uuid1234);
but I can't get any syntax to work. I tried
create or replace function insertTable1 (junk integer)
RETURNS UUID
LANGUAGE plpgsql AS
$func$
declare
myUuid UUID;
BEGIN
insert into table1 (blah) values (junk) returning uuid into myUuid;
return myUuid;
END
$func$;
then doing something like set my.var.uuid = select insertTable1(1234) and insert into table2 (table1Uuid my.var.uuid) with various uses of current_setting
I have read many posts on SO, but can't find one that allows the value of the variable to outlast the function and be used