John.zero
John.zero

Reputation: 3

How to use UPDATE in PostgreSQL with variable table?

Example:

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

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

How to do this loop?

Upvotes: 0

Views: 5558

Answers (1)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 657122

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;

Upvotes: 3

Related Questions