문제

Is it possible in PostgreSQL to update a table and insert data into another table at the same time.

Like

UPDATE table1
SET column4=true
AND INSERT into table2
SELECT column1, column2, column3
FROM table 1
WHERE column1="peter"
;
도움이 되었습니까?

해결책

On Postgres 9.1 or later you can use something like:

WITH source AS (UPDATE table1
                SET column4=true
                WHERE column1='peter'
                RETURNING column1, column2, column3)
INSERT INTO table2 
SELECT column1, column2, column3
FROM source;

다른 팁

You can execute multiple statements inside a transaction, so it will still be an atomic change to your data.

BEGIN;

UPDATE table1
SET column4=true;

INSERT into table2
SELECT column1, column2, column3
FROM table 1
WHERE column1="peter";

COMMIT;

If for whatever reason the insert fails, the entire transaction will fail, and the changes will be backed out, including the update that was executed before the insert statement.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top