2

I have an update statement with returning statement.

What I want is to put the result into a variable or temp table.

update my_table
set something = 'x'
where id ...
returning *;

I tried to that using the execute statement and e.g. returning row_to_json(my_table.*) but the variable, off cause, only contains the first row returned from the update.

1 Answer 1

3

Use a CTE with the UPDATE-RETURNING statement in it, then use that in the INSERT:

CREATE TEMP TABLE t (i int, j int);
CREATE TEMP TABLE u (i int, j int);
INSERT INTO u VALUES (1, 1), (2, 2), (3, 3);  

WITH updated AS (
  UPDATE u
  SET i = i * 10
  WHERE i < 3
  RETURNING *
)
INSERT INTO t
SELECT *
FROM updated;

SQLFiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.