1

I have a Postgres database with 3 tables, say A, B and C. I want to select data from table A and loop through each row checking the value in one of the columns and then insert the data into table B or table C based on the condition.

How can I do this, can some one please post a sample script please. I prefer plpgsql (using PGAdmin3).

4

3 回答 3

2

您不需要游标,不需要 plpgsql,甚至不需要数据修改 CTE,它允许您在单个 SQL 语句中执行此操作。

只需运行两个简单的INSERT语句。如果您想确保应用全部或全部应用,请将它们放入事务中:

BEGIN;

INSERT INTO B (col1, col2)
SELECT col1, col2
FROM   A
WHERE  col_cond = 'something';

INSERT INTO C (col1, col2)
SELECT col1, col2
FROM   A
WHERE  col_cond IS DISTINCT FROM 'something';

COMMIT;
于 2013-07-26T03:59:47.957 回答
0

表 A 上选择语句的用户光标,请参见此链接

在游标内,您可以检查条件并在 B 或 C 上运行插入语句

有关代码示例,请参见此链接

干杯!!

于 2013-07-26T03:04:01.630 回答
0

键入以下命令:

begin;
insert into table_name as select * from table_name2 where Name="?";
commit;
于 2013-07-26T04:14:18.693 回答