postgres autoincrement not updated on explicit id inserts

前端 未结 3 1710
清酒与你
清酒与你 2020-12-04 21:26

I have the following table in postgres:

CREATE TABLE \"test\" (
    \"id\" serial NOT NULL PRIMARY KEY,
    \"value\" text
)

I am doing fol

3条回答
  •  再見小時候
    2020-12-04 21:42

    It can be done automatically using a trigger. This way you are sure that the largest value is always used as the next default value.

    CREATE OR REPLACE FUNCTION set_serial_id_seq()
    RETURNS trigger AS
    $BODY$
      BEGIN
       EXECUTE (FORMAT('SELECT setval(''%s_%s_seq'', (SELECT MAX(%s) from %s));',
       TG_TABLE_NAME,
       TG_ARGV[0],
       TG_ARGV[0],
       TG_TABLE_NAME));
        RETURN OLD;
       END;
    $BODY$
    LANGUAGE plpgsql;  
    
    CREATE TRIGGER set_mytable_id_seq
    AFTER INSERT OR UPDATE OR DELETE
    ON mytable
    FOR EACH STATEMENT
      EXECUTE PROCEDURE  set_serial_id_seq('mytable_id');
    

    The function can be reused for multiple tables. Change "mytable" to the table of interest.

    For more info regarding triggers:

    https://www.postgresql.org/docs/9.1/plpgsql-trigger.html

    https://www.postgresql.org/docs/9.1/sql-createtrigger.html

提交回复
热议问题