database - Postgresql : Loop thorugh each table and check for column? -
i trying write simple sql
query in pgadmin
loop through each table in database , change specified column name if exists. have never coded in sql
after searching through many forums have managed come with:
do begin in select table_name information_schema.tables loop if select column_name information_schema.columns table_name = 'i.table_name' alter table i.table_name rename column old_column_name new_column_name end if; end loop;
any great.
you can skip information_schema.tables
entirely. just:
do $$ declare rec record; begin rec in select table_schema, table_name, column_name information_schema.columns column_name = 'x' loop execute format('alter table %i.%i rename column %i newname;', rec.table_schema, rec.table_name, rec.column_name); end loop; end; $$ language plpgsql;
with appropriate substitutions 'x'
, newname
. or make function takes them parameters, whatever.
Comments
Post a Comment