从插入结果设置 Postgresql 变量以备将来使用

Setting Postgresql variable from result of insert for future use

我有一个 table,带有插入时生成的 UUID 密钥。我需要在以后的多个插入中使用该密钥,并希望将其存储在一个变量中。

    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);

我想我可以确保以后所有插入到 TABLE2 的操作都与插入到 TABLE1 的操作在同一个会话(可能是同一个脚本)中。想做点像

uuid1234 = INSERT INTO TABLE1 (blah) values (1234);
uuid6789 = INSERT INTO TABLE1 (blah) values (6789);
.....
INSERT INTO TABLE2 (table1Uuid uuid1234);

但我无法使用任何语法。我试过了

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$;

然后用 current_setting 的各种用途做一些类似 set my.var.uuid = select insertTable1(1234)insert into table2 (table1Uuid my.var.uuid) 的事情 我已经阅读了很多关于 SO 的帖子,但找不到允许变量值比函数更持久并被使用的帖子

这是你想要的吗?

with t1 as (
    insert into table1 (blah) values (1234), (6789)
    returning *
)
insert into table2 (table1Uuid)
select uuid from t1 where blah = 1234;

CTE 在 table1 中插入几行,然后外部查询在 table2 中插入为 blah 1234 生成的 uuid

请注意,如果您在 CTE 中多次插入 1234,外部查询将在 table2 中创建同样多的行。

或者,您可以在另一个 CTE 中隔离第一个插入:

with 
    t1 as (insert into table1 (blah) values (1234) returning *),
    t2 as (insert into table1 (blah) values (456), (789))
insert into table2 (table1Uuid) select uuid from t1