0

Example:

Table=["category1","category2","category3"]

for varTable in Table:
    cr.execute('update varTable SET id=%s,WHERE id=%s)
     ........
       ....

How to do this loop?

1 Answer 1

3

Use dynamic SQL for that. The default is to use plpgsql with EXECUTE.
Create a function or use a DO statement for ad-hoc execution.

Dynamic SQL

CREATE OR REPLACE FUNCTION f_up(_new_id int, _old_id int)
  RETURNS void AS
$BODY$
DECLARE
    _tbl text[] := '{category1,category2,category3}';
    t    text;

BEGIN

FOREACH t IN ARRAY _tbl
LOOP
    EXECUTE '
    UPDATE ' || t || '
    SET    id = $1
    WHERE  id = $2'
    USING  _new_id, _old_id;
END LOOP;

END;
$BODY$ LANGUAGE plpgsql;

Call:

SELECT f_up(23, 45);

There are lots of similar answers on SO. Search for , and EXECUTE for more examples and explanation.

Plain SQL

If plpgsql is still black magic to you, you can solve this simple case quite effectively with a data-modifying CTE. Requires PostgreSQL 9.1 - for data-modifying CTE.

WITH vals AS (
    SELECT 23 AS new_id, 45 AS old_id -- provide values once
    )
    , a AS (
    UPDATE category1
    SET    id = v.new_id
    FROM   vals v
    WHERE  id = v.old_id
    )
    , b AS (
    UPDATE category2
    SET    id = v.new_id
    FROM   vals v
    WHERE  id = v.old_id
    )
UPDATE category3
SET    id = v.new_id
FROM   vals v
WHERE  id = v.old_id;
Sign up to request clarification or add additional context in comments.

6 Comments

@John.zero: I added a plain SQL alternative. :)
Plain SQL will be too long if I have lots of table to change.THK
I just try Dynamic SQL in my Postgre SQL .there is an error"error: Operator is not Unique: unknown || text[] LINE 2: UPDATE '||_tbl||' ^"
@John.zero: My bad, fixed the query.
I need to add a variable in :CREATE OR REPLACE FUNCTION f_up(varTable,_new_id int, _old_id int),how to change the code?
|

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.