Update column in multiple tables
Asked Answered
R

1

2

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?

Resentment answered 17/12, 2014 at 13:58 Comment(1)
Dynamic SQL - PL/PgSQL, EXECUTE format(...) USING .... Also, if you ever need to do this it's probably a sign of problematic database design.Routh
S
3

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:

Information schema or system catalog?

Sigmoid answered 17/12, 2014 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.