Set AUTO_INCREMENT value through variable in MySql

依然范特西╮ 提交于 2019-12-12 20:26:36

问题


I have a table with an auto_increment column. I save the last value of the column in another table called ids_tbl, and when mysql restarts, read the value from ids_tbl and re-set the AUTO_INCREMENT value. If I do this:

alter table outgoing_tbl auto_increment=500; 

it works

But if I do this

select @max_id:= max_id FROM ids_tbl;
alter table outgoing_tbl auto_increment=@max_id; 

or if I do this:

select @max_id:= max_id FROM ids_tbl;
alter table outgoing_tbl auto_increment=(select @max_id); 

Then it does not work, how do I set the auto increment value throgh a variable?


回答1:


Use the below code. This is working fine. And follow the MySQL prepared statement https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html

SET @max_id = (SELECT MAX(id) FROM `ids_tbl` );
SET @sql = CONCAT('ALTER TABLE `outgoing_tbl` AUTO_INCREMENT = ', @max_id);
PREPARE st FROM @sql;
EXECUTE st;


来源:https://stackoverflow.com/questions/46622690/set-auto-increment-value-through-variable-in-mysql

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