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?
Syntax for MySQLMySQL uses the AUTO_INCREMENT keyword to perform an auto-increment feature. By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record. VALUES ('Lars','Monsen'); The SQL statement above would insert a new record into the "Persons" table.
If you're looking to add auto increment to an existing table by changing an existing int column to IDENTITY , SQL Server will fight you. You'll have to either: Add a new column all together with new your auto-incremented primary key, or. Drop your old int column and then add a new IDENTITY right after.
If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu. When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.
To obtain the value immediately after an INSERT , use a SELECT query with the LAST_INSERT_ID() function. For example, using Connector/ODBC you would execute two separate statements, the INSERT statement and the SELECT query to obtain the auto-increment value.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With