Using PostgreSQL (8.x), I need to skip a block of sequence numbers automatically , eg after giving out 49999 I want the next id to be 70000 not 50000
What is the correct/safest way of doing this?
NB: I originally posted a very similar question How can I forward a primary key sequence in Django safely? but I have the feeling that this must be done at database level (concurrency issues)...
I believe I've found a way:
You can use a trigger, that checks the actual value of the sequence after an insert statement and change it for the value that you want.
I think that this snippet should do the job
CREATE OR REPLACE FUNCTION change_sequence() RETURNS TRIGGER AS $change_sequence$
DECLARE
current_value INTEGER;
BEGIN
current_value := currval('your_sequence');
IF current_value = 49999 THEN
setval ('you_sequence', 70000, false);
END IF;
RETURN NULL;
END;
$change_sequence$ LANGUAGE plpgsql;
-- DROP TRIGGER check_pkey ON your_table;
CREATE TRIGGER check_pkey
AFTER INSERT ON your_table
EXECUTE PROCEDURE change_sequence();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.