Chr*_*ris 5 sql postgresql postgresql-9.2
有没有办法可以在我的 PostgreSQL 数据库中的所有模式中将所有名为“location”的列名重命名为“location_name”?
我对 SQL 相当陌生,并且知道有一个 ALTER TABLE 命令,但不知道是否可以以某种方式循环遍历所有表?
为此,您需要使用匿名 PL/pgSQL 块以自动方式执行此操作的动态 SQL:
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;
$$
Run Code Online (Sandbox Code Playgroud)
如果您有多个架构或您的表不在public架构中,请用where table_schema = 'public'适当的限制替换条件。
如果您拥有超级用户权限,您可以在系统目录中一次性进行更改:
UPDATE pg_attribute
SET attname = 'location_name'
WHERE attname = 'location';
Run Code Online (Sandbox Code Playgroud)