我想强制一个表的自动增量字段的一些值,我尝试了这样:

ALTER TABLE product AUTO_INCREMENT = 1453

AND

ALTER SEQUENCE product  RESTART WITH 1453;
ERROR:  relation "your_sequence_name" does not exist

我有一个表产品与Id和名称字段


当前回答

节点脚本:修复所有表identity: auto-increment / nextval,基于上次插入它。

const pg = require('pg');
const { Client } = pg;

const updateTables = async () => {

  const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'my-database',
    password: 'postgres',
    port: 5432,
  });

  await client.connect();

  console.log('Connected');

  const execQuery = async (queryStr, params = []) => {
    return new Promise((resolve, reject) => {
      client.query(queryStr, params, (error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      })
    })
  }

  const tablesRes = await execQuery(`
    SELECT table_name
    FROM information_schema.tables
    WHERE table_type='BASE TABLE'
    AND table_schema='public';
  `)

  const tables = tablesRes.rows.map(row => row.table_name);

  tables.map(async tableName => {
    let lastId;
    try {
      const res = await execQuery(`SELECT id from "${tableName}" ORDER BY id DESC LIMIT 1`);
      lastId = res.rows[0].id;
    } catch (e) {}

    if (lastId) {
      const nextId = lastId + 1;
      const queryStr = `ALTER SEQUENCE ${tableName}_id_seq RESTART WITH ${nextId}`;
      await execQuery(queryStr);
      console.log(tableName, queryStr);
    }
  })

};

updateTables();

其他回答

ALTER SEQUENCE public."Table_Id_seq"
RESTART 50;

这个问题对我很管用。Postgresql版本14

如果你有一个带有IDENTITY列的表,你想要重置下一个值,你可以使用以下命令:

ALTER TABLE <table name> 
    ALTER COLUMN <column name> 
        RESTART WITH <new value to restart with>;

下面的命令会自动执行此操作:这也会删除表中的所有数据。所以要小心。

TRUNCATE TABLE someTable RESTART IDENTITY;

2021年Postgres 11.12

ALTER SEQUENCE没有为我工作,它以某种方式将其重置为null。 对我有用的是:

SELECT setval('<table>_<column>_seq', 5);

下面是你要找的命令,假设你的product表序列是product_id_seq:

ALTER SEQUENCE product_id_seq RESTART WITH 1453;