Alter auto-generated sequence

别等时光非礼了梦想. 提交于 2020-01-05 08:03:34

问题


I use this to create auto-incremented id columns:

  id  BIGSERIAL                                -- psql
  id  BIGINT GENERATED BY DEFAULT AS IDENTITY  -- hsql

Now in unit tests i'd like to reset those sequences between tests.

Is this possible? I target PostgreSQL and HSQLDB


回答1:


TRUNCATE table RESTART IDENTITY;

http://www.postgresql.org/docs/9.2/static/sql-truncate.html
http://hsqldb.org/doc/guide/dataaccess-chapt.html#dac_truncate_statement




回答2:


For PostgreSQL, you can use the pg_get_serial_sequence function to discover the name of the underlying sequence used to maintain the auto-increment, and the setval function to then manipulate it, e.g. to make the sequence match the highest value in the table after manually inserting or deleting rows:

Select setval(
    pg_get_serial_sequence('table_name', 'column_name'),
    (Select Max(column_name) From table_name),
    TRUE
);

The "true" is optional (default behaviour); it tells the sequence the value provided has been used, and to increment before providing the next value. See the Postgres documentation

On an empty table, you want the next value to be 1, but 0 is out of range, so you would pass FALSE:

 Select setval(pg_get_serial_sequence('table_name', 'column_name'), 1, FALSE);


来源:https://stackoverflow.com/questions/15898772/alter-auto-generated-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!