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

从插入结果设置Postgresql变量以备将来使用,sql,postgresql,sql-insert,Sql,Postgresql,Sql Insert,我有一个带有UUID键的表,该键是在insert时生成的。我需要在以后的多次插入中使用该键,并希望将其存储在变量中 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

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

    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);
我想我可以确保将来插入到表2中的所有内容都与表1中的内容在同一个会话中(可能是同一个脚本)。我想做点什么

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$;
然后执行类似于
set my.var.uuid=select insertTable1(1234)
insert-into-table2(table1uid 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在
表1
中插入几行,然后外部查询在
表2
中插入为
blah
1234
生成的
uuid

请注意,如果在CTE中多次插入
1234
,则外部查询将在
表2中创建尽可能多的行

此外,您可以在另一个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 
这是你想要的吗

with t1 as (
    insert into table1 (blah) values (1234), (6789)
    returning *
)
insert into table2 (table1Uuid)
select uuid from t1 where blah = 1234;
CTE在
表1
中插入几行,然后外部查询在
表2
中插入为
blah
1234
生成的
uuid

请注意,如果在CTE中多次插入
1234
,则外部查询将在
表2中创建尽可能多的行

此外,您可以在另一个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 

我不能保证blah值是唯一的,所以我需要特定于该特定插入的uuid(我在示例代码中没有输入其他列)。这是否意味着表2的所有插入都必须在1语句中?我可能会在表1中插入大约20个,然后在表2中插入100个。似乎带有
的1条语句
将变得不合适。我不能保证blah值是唯一的,因此我需要特定于该插入的uuid(我在示例代码中没有放入其他列)。这是否意味着表2的所有插入必须在1条语句中?我可能会在表1中插入大约20个,然后在表2中插入100个。似乎有一条语句
会变得不合适。