是否可以在postgresql中对某个类型的所有列进行批量重命名。我有一系列的表都有几何类型列(每个表只有1个),名称如“the_geom”,“geom”,“SP_GEOMETRY”等,由于使用了不同的导入工具,它们都有不同的名称。
我希望能够将它们全部重命名为“the_geom”或“geom”。
答案 0 :(得分:4)
运行此查询以生成所需的所有DDL语句:
SELECT 'ALTER TABLE ' || quote_ident(n.nspname) || '.' || quote_ident(c.relname)
|| ' RENAME column ' || quote_ident(a.attname) || ' TO geom;'
FROM pg_catalog.pg_attribute a
JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE a.attnum >= 1
AND a.atttypid = 'geometry'::regtype::oid
AND a.attname <> 'geom'
AND NOT a.attisdropped
AND n.nspname !~~ 'pg_%' -- exclude catalog & temp tables, to be sure
-- AND n.nspname = 'myschema' -- target specific schema only?
答案 1 :(得分:1)
查询系统目录并生成命令通常是最简单的方法。像这样:
select
'alter table ' || quote_ident(nspname) || '.' || quote_ident(relname)
|| ' rename column ' || quote_ident(attname)
|| ' to ' || quote_ident('xxx')
from pg_attribute
join pg_class on pg_class.oid = pg_attribute.attrelid
join pg_namespace on pg_namespace.oid = pg_class.relnamespace
where atttypid = 'geometry'::regtype and (attname ~* 'geom')
and not attisdropped and attnum > 0 and pg_class.oid >= 16384