pg数据库统一更新序列值,解决序列值不一致问题

CREATE OR REPLACE FUNCTION "public"."update_sequence_values"() 
  RETURNS TABLE("var_table_schema" text, "var_table_name" text, "old_max_id" int8, "new_max_id" int8) AS $$
DECLARE
  table_rec RECORD;
  max_id BIGINT;         -- 将数据类型更改为 BIGINT
  old_max_id_val BIGINT; -- 将数据类型更改为 BIGINT
BEGIN
  -- 创建临时表以保存更新的序列值
  DROP TABLE IF EXISTS temp_sequence_updates;
  CREATE TEMP TABLE temp_sequence_updates (
    var_table_schema TEXT,
    var_table_name TEXT,
    old_max_id BIGINT,  -- 修改数据类型为 BIGINT
    new_max_id BIGINT   -- 修改数据类型为 BIGINT
  );

  -- 遍历指定模式下所有包含自增主键的表
  FOR table_rec IN (
    SELECT DISTINCT
      table_schema,
      table_name,
      column_name,
      data_type
    FROM information_schema.columns
    WHERE 
      table_schema = 'public'
      AND column_default LIKE 'nextval%'
      AND (data_type = 'integer' OR data_type = 'bigint')
  ) LOOP
    EXECUTE format('SELECT MAX(%I) FROM %I.%I;', table_rec.column_name, table_rec.table_schema, table_rec.table_name) INTO max_id;

    -- 更新序列
    IF max_id IS NOT NULL THEN
      EXECUTE format('SELECT setval(pg_get_serial_sequence(''%I'', ''%s''), %s, false);', table_rec.table_name, replace(table_rec.column_name, '"','') , max_id + 1);

      -- 记录更新操作的日志信息
      INSERT INTO temp_sequence_updates (var_table_schema, var_table_name, old_max_id, new_max_id) VALUES (table_rec.table_schema, table_rec.table_name , max_id, max_id + 1);
    END IF;
  END LOOP;

  -- 返回更新操作的日志信息
  RETURN QUERY SELECT * FROM temp_sequence_updates;
END;

$$ LANGUAGE plpgsql;







	
SELECT * FROM update_sequence_values();

你可能感兴趣的:(数据库)