Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set AUTO_INCREMENT value through variable in MySql

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?

like image 413
Sinai Avatar asked Oct 07 '17 16:10

Sinai


People also ask

Can we insert auto increment value in MySQL?

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.

How do I set up auto increment?

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.

How do I automatically generate numbers in MySQL?

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.

How can insert auto increment value in SQL query?

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.


1 Answers

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;
like image 164
sheraz Avatar answered Nov 09 '22 12:11

sheraz