How to use UPDATE in PostgreSQL with variable table?
示例:
1 2 3 4 5 6 | TABLE=["category1","category2","category3"] FOR varTable IN TABLE: cr.execute('update varTable SET id=%s,WHERE id=%s) ........ .... |
这个循环怎么做?
为此使用动态 SQL。默认是使用带有
创建一个函数或使用
动态 SQL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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; |
呼叫:
1 | SELECT f_up(23, 45); |
关于 SO 有很多类似的答案。搜索 dynamic-sql、plpgsql 和
纯 SQL
如果 plpgsql 对您来说仍然是黑魔法,您可以使用数据修改 CTE 非常有效地解决这个简单的案例。需要 PostgreSQL 9.1 - 用于数据修改 CTE。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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; |