例子:
Table=["category1","category2","category3"]
for varTable in Table:
cr.execute('update varTable SET id=%s,WHERE id=%s)
........
....
这个循环怎么做?
例子:
Table=["category1","category2","category3"]
for varTable in Table:
cr.execute('update varTable SET id=%s,WHERE id=%s)
........
....
这个循环怎么做?
为此使用动态 SQL。默认是使用 plpgsql 和EXECUTE
.
创建一个函数或使用一条DO
语句进行临时执行。
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;
称呼:
SELECT f_up(23, 45);
SO上有很多类似的答案。搜索dynamic-sql、plpgsql以及EXECUTE
更多示例和解释。
如果 plpgsql 对您来说仍然是黑魔法,您可以使用数据修改 CTE 非常有效地解决这个简单的案例。需要 PostgreSQL 9.1 - 用于数据修改 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;