2011-12-07 70 views
1

是否有可能对postgresql中的某个类型的所有列进行批量重命名。我有一系列带有“the_geom”,“geom”,“SP_GEOMETRY”等名称的几何表格,每个表格都有几何类型列(每个表只有1个表格),由于使用了不同的导入工具,它们都有不同的名称。大量重命名列postgresql

我希望能够将它们全部重命名为“the_geom”或“geom”。

+0

哪个版本是你吗? – Kuberchaun

+0

我在版本8.4 –

回答

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 
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?