重置自动增量 ID。
重置自动增量 ID
根据数据库中的当前值,将数据库中的所有自动增量列更新为可能的最小值。我们需要在清理数据库后执行此操作。
在存储过程中使用准备好的语句:
drop PROCEDURE if exists reset_autoincrement;
DELIMITER //
CREATE PROCEDURE reset_autoincrement (IN schemaName varchar(255))
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE o_name VARCHAR(255);
DECLARE o_table VARCHAR(255);
DECLARE cur1 CURSOR FOR SELECT COLUMN_NAME, TABLE_NAME FROM information_schema.`COLUMNS` WHERE extra LIKE '%auto_increment%' and table_schema=schemaName;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO o_name, o_table;
IF done THEN
LEAVE read_loop;
END IF;
set @qry1 = concat('SELECT MAX(`',o_name,'`) + 1 as autoincrement FROM `',o_table,'` INTO @ai');
PREPARE stmt1 FROM @qry1;
EXECUTE stmt1;
IF @ai IS NOT NULL THEN
SELECT o_name, o_table;
select @qry1;
select @ai;
set @qry2 = concat('ALTER TABLE `',o_table,'` AUTO_INCREMENT = ', @ai);
select @qry2;
PREPARE stmt2 FROM @qry2;
EXECUTE stmt2;
END IF;
END LOOP;
CLOSE cur1;
END //
DELIMITER ;
call reset_autoincrement('my_schema_name');