简体   繁体   English

在PostgreSQL中重命名具有特定列名的所有表中的所有列?

[英]Rename all columns from all tables with specific column name in PostgreSQL?

Is there a way I can rename all column names that are called 'location' to 'location_name' within all schemas in my PostgreSQL database? 有没有办法可以在PostgreSQL数据库的所有模式中将所有名为'location'的列名重命名为'location_name'?

I am fairly new to SQL and am aware there is an ALTER TABLE command but don't know if it is possible to somehow loop through all tables? 我是SQL的新手,我知道有一个ALTER TABLE命令,但不知道是否有可能以某种方式遍历所有表?

You need dynamic SQL for this using an anonymous PL/pgSQL block to do this in an automated way: 您需要动态SQL,使用匿名PL / pgSQL块以自动方式执行此操作:

do
$$
declare
  l_rec record;
begin
  for l_rec in (select table_schema, table_name, column_name 
                from information_schema.columns 
                where table_schema = 'public' 
                  and column_name = 'location') loop
     execute format ('alter table %I.%I rename column %I to %I_name', l_rec.table_schema, l_rec.table_name, l_rec.column_name, l_rec.column_name);
  end loop;
end;
$$

If you have multiple schemas or your tables are not in the public schema, replace the condition where table_schema = 'public' with the appropriate restriction. 如果您有多个模式或者您的表不在public模式中,请将where table_schema = 'public'的条件替换为适当的限制。

If you have superuser privileges you can make the changes in one sweep in the system catalogs: 如果您具有超级用户权限,则可以在系统目录中的一次扫描中进行更改:

UPDATE pg_attribute
SET attname = 'location_name'
WHERE attname = 'location';

I think the closest you will get is running something like this: 我认为你得到的最接近的是运行这样的东西:

SELECT FORMAT(
  'ALTER TABLE %I.%I.%I RENAME COLUMN %I TO %I;',
  catalog_name,
  schema_name,
  table_name,
  column_name,
  'location_name'
)
FROM information_schema.columns
WHERE column_name = 'location';

If you run that in psql, you can follow it with \\gexec and it should work. 如果你在psql中运行它,你可以用\\gexec跟随它,它应该工作。

You can fetch all location columns in your database with 您可以使用获取数据库中的所有location

SELECT * FROM information_schema.columns WHERE column_name = 'location';

And probably use some programming language to then execute all rename queries. 并且可能使用一些编程语言来执行所有重命名查询。 There are information_schema tables in almost every database management system (although, they are sometimes called/structured differently). 几乎每个数据库管理系统都有information_schema表(尽管它们有时被称为/结构不同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM