【问题标题】:Mass rename columns postgresql批量重命名列 postgresql
【发布时间】:2011-12-07 23:38:37
【问题描述】:

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

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

【问题讨论】:

  • 你是什么版本的?

标签: sql postgresql postgis


【解决方案1】:

运行此查询以生成所需的所有 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?

【讨论】:

    【解决方案2】:

    查询系统目录并生成命令通常是最简单的方法。像这样的:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 2012-11-15
      • 2013-12-19
      相关资源
      最近更新 更多