我在PostgreSQL
中有这段代码:
for row in select .... from .... where ....
loop
insert into A(id1,id2,id3,quantity)
select aa,bb,1,quantity
from func1(row.idfirst);
end loop;
我想用同一个查询做另一个INSERT
所以我可以这样做:
for row in select .... from .... where ....
loop
insert into A(id1,id2,id3,quantity)
select aa,bb,1,quantity
from func1(row.idfirst);
insert into B(first,second,third,forth)
select aa,bb,1,quantity
from func1(row.idfirst);
end loop;
事情是,它是相同代码的冗余......而且func1
也是一个巨大的功能。它需要很长时间才能运行,而且我不会疯狂地运行它两次。
是否有任何解决方案可以使用相同的select
查询进行两次插入?
答案 0 :(得分:2)
您可以在PostgreSQL 9.1+中使用CTE,如下所示:
WITH CTE AS (
INSERT INTO A(id1,id2,id3,quantity)
SELECT aa,bb,1,quantity
FROM func1(row.idfirst);
RETURNING id1,id2,id3,quantity
)
INSERT INTO B(first,second,third,forth)
SELECT id1,id2,id3,quantity
FROM CTE;