0

我有一个包含许多表的 Postgres 数据库。我想声明一个函数,将所有表的所有 auto_increment 值 (next_value) 重置为表的 max(id)。例如,如果sample_tablemax(id)22

postgres=# SELECT MAX(id) + 1 FROM sample_table;
 ?column? 
----------
       22
(1 row)

虽然表的next_value7

postgres=# SELECT nextval('"public"."sentry_project_id_seq"'::regclass);
 nextval 
---------
       7
(1 row)

我想通过以下方式将所有表的next_value设置为它们的max(id)

SELECT setval('auth_user_id_seq', (SELECT MAX(id) from "auth_user"));

为此,我通过以下方式声明了一个名为reset_auto_increment的函数:

CREATE OR REPLACE FUNCTION reset_auto_increment(username IN VARCHAR) RETURNS void AS $$
DECLARE
        statements CURSOR FOR
            SELECT tablename FROM pg_tables
            WHERE tableowner = username AND schemaname = 'public';
    BEGIN
        FOR stmt IN statements LOOP
            EXECUTE 'SELECT setval(' || concat(stmt.tablename, '_id_seq') || ' , (SELECT MAX(id) from ' || quote_ident(stmt.tablename) || '));';
        END LOOP;
    END;
$$ LANGUAGE plpgsql;

但是上面语句声明的函数有以下错误:

postgres=# select reset_auto_increment('postgres');
**ERROR:  column "_id_seq" does not exist**
LINE 1: SELECT 'SELECT setval(' || concat(stmt.tablename, "_id_seq")...
                                                          ^
QUERY:  SELECT 'SELECT setval(' || concat(stmt.tablename, "_id_seq") || ' , (SELECT MAX(id) from ' || quote_ident(stmt.tablename) || '));'
CONTEXT:  PL/pgSQL function reset_auto_increment(character varying) line 8 at EXECUTE

如何纠正这个功能?

4

0 回答 0