postgres: find all integer columns with its current max value in it

ぃ、小莉子 提交于 2019-12-13 17:14:22

问题


How to find all integer typed primary key columns with its current max value in it from all tables from all databases in Postgres instance?

I want to find all the int typed primary key columns from all tables which are nearing to overflow its max value 2147483647.


回答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;$$;

Then you can get a list with

SELECT * FROM intpkmax();


来源:https://stackoverflow.com/questions/42712604/postgres-find-all-integer-columns-with-its-current-max-value-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!