Created
April 28, 2011 20:42
-
-
Save DBNess/947292 to your computer and use it in GitHub Desktop.
Updates all serial sequences for ID columns only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--Updates all serial sequences for ID columns only | |
CREATE OR REPLACE FUNCTION update_id_sequences() | |
RETURNS boolean AS | |
$BODY$ | |
DECLARE table_record record; | |
DECLARE table_name text; | |
DECLARE update_sql text; | |
BEGIN | |
FOR table_record IN SELECT pc.relname FROM pg_class pc WHERE pc.relkind = 'r' AND EXISTS (SELECT 1 FROM pg_attribute pa WHERE pa.attname = 'id' AND pa.attrelid = pc.oid) LOOP | |
table_name = table_record.relname::text; | |
EXECUTE 'SELECT setval(pg_get_serial_sequence(' || quote_literal(table_name) || ', ' || quote_literal('id')::text || '), MAX(id)) FROM ' || table_name || ' | |
WHERE EXISTS (SELECT 1 FROM ' || table_name || ')'; | |
END LOOP; | |
RETURN true; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment