【问题标题】:postgres: find all integer columns with its current max value in itpostgres:查找所有具有当前最大值的整数列
【发布时间】:2017-03-10 07:24:33
【问题描述】:

如何从 Postgres 实例中所有数据库的所有表中找到所有整数类型的主键列及其当前最大值?

我想从所有接近溢出其最大值 2147483647 的表中查找所有 int 类型的主键列。

【问题讨论】:

    标签: sql postgresql information-schema


    【解决方案1】:
    CREATE OR REPLACE FUNCTION intpkmax() RETURNS
       TABLE(schema_name name, table_name name, column_name name, max_value integer)
       LANGUAGE plpgsql STABLE AS
    $$BEGIN
       /* loop through tables with a simgle integer column as primary key */
       FOR schema_name, table_name, column_name IN
          SELECT sch.nspname, tab.relname, col.attname
             FROM pg_class tab
                JOIN pg_constraint con ON con.conrelid = tab.oid
                JOIN pg_attribute col ON col.attrelid = tab.oid
                JOIN pg_namespace sch ON sch.oid = tab.relnamespace
             WHERE con.contype = 'p'
                AND array_length(con.conkey, 1) = 1
                AND col.atttypid = 'integer'::regtype
                AND NOT col.attisdropped
       LOOP
          /* get the maximum value of the primary key column */
          EXECUTE 'SELECT max(' || quote_ident(column_name) ||
                  ') FROM ' || quote_ident(schema_name) ||
                  '.' || quote_ident(table_name) || ''
             INTO max_value;
          /* return the next result */
          RETURN NEXT;
       END LOOP;
    END;$$;
    

    然后你可以得到一个列表

    SELECT * FROM intpkmax();
    

    【讨论】:

      猜你喜欢
      • 2020-08-24
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2015-07-07
      相关资源
      最近更新 更多