Update column in multiple tables

风格不统一 提交于 2020-01-15 05:36:09

问题


Let's say I have a column called partner in multiple tables within one schema:

select table_name from information_schema.columns where column_name = 'partner';

How would I update all columns where value partner = 100 to partner = 101?


回答1:


For a one-time operation, a DO statement executing dynamic SQL should serve just fine:

DO
$do$
DECLARE
   _tbl text;
BEGIN
FOR _tbl  IN
    SELECT quote_ident(table_name)  -- escape identifier!
    FROM   information_schema.columns
    WHERE  table_schema = 'public'  -- your schema (!!)
    AND    column_name = 'partner'  -- your column name
LOOP
   RAISE NOTICE '%',
-- EXECUTE
  'UPDATE ' || _tbl || ' SET partner = 101 WHERE partner = 100';
END LOOP;
END
$do$

Inspect the generated code before you comment RAISE and uncomment the EXECUTE.

This is a largely simplified version of the more versatile function in this related answer with more explanation:

  • Changing all zeros (if any) across all columns (in a table) to... say 1

Information schema or system catalog?

  • How to check if a table exists in a given schema


来源:https://stackoverflow.com/questions/27527231/update-column-in-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!