currval has not yet been defined this session, how to get multi-session sequences?

前端 未结 5 1154
再見小時候
再見小時候 2020-12-25 11:38

My objective is to get a primary key field automatically inserted when inserting new row in the table.

How to get a sequence going from session to session in Postg

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-25 11:58

    This may be simpler than you think ...

    My objective is to get a primary key field automatically inserted when inserting new row in the table.

    Just set the default value of the column:

    ALTER TABLE tbl ALTER COLUMN tbl_id SET DEFAULT nextval('my_seq'::regclass);
    

    Or simpler yet, create the table with a serial type for primary key to begin with:

    CREATE TABLE tbl(
      tbl_id serial PRIMARY KEY
     ,col1 txt
      -- more columns
    );
    

    It creates a dedicated sequence and sets the default for tbl_id automatically.

    This way tbl_id is assigned the next value from the attached sequence automatically if you don't mention it in the INSERT. Works with any session, concurrent or not.

    INSERT INTO tbl(col1) VALUES ('foo');
    

    If you want the new tbl_id back to do something with it:

    INSERT INTO tbl(col1) VALUES ('foo') RETURNING tbl_id;
    

提交回复
热议问题