CREATE OR REPLACE VIEW sequence_setvals AS 
 SELECT ((((('SELECT setval(''"' || cs.relname) || '"'', max("') || a.attname) || '")) FROM
"') || c.relname) || '";' AS expr
   FROM pg_class c, pg_class cs, pg_attribute a, pg_attrdef d
  WHERE cs.relkind = 'S' AND d.adsrc ~ cs.relname AND c.oid = a.attrelid AND c.oid = d.adrelid AND d.adnum = a.attnum;


CREATE OR REPLACE FUNCTION sys_refresh_sequences()
  RETURNS integer AS
'
    DECLARE
        myseq RECORD;
    BEGIN
        FOR myseq IN select * from sequence_setvals LOOP
            BEGIN
                RAISE NOTICE ''Executing - %'', myseq.expr;
                EXECUTE myseq.expr;
            EXCEPTION WHEN numeric_value_out_of_range THEN
                RAISE NOTICE ''Nincs egy tetel sem a tablaban, ezert az aktualizalas nem tortent meg.'';
                -- Do nothing, and loop to try the UPDATE again.
            END;
        END LOOP;

        return 1;
    END;
'
  LANGUAGE plpgsql VOLATILE;