如何选择字段值并使用for循环将它们插入另一个表中

时间:2017-11-30 20:32:44

标签: postgresql for-loop plpgsql

我想在Postgres中编写一个函数,从表A中选择一列,然后遍历这些值并将它们插入到表B中。

这是我到目前为止所做的:

declare 
    aid integer
begin
    for aid in select a_id from table_a
    loop
        insert into table_b (a_id)
            values (aid)
    end loop;
end;

但是,我在第for aid in select a_id from table_a行遇到了语法错误。这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您不需要循环 - 只需一个insert-select语句:

INSERT INTO table_b (a_id)
SELECT a_id FROM table_a