It is possbile set/reset the AUTO_INCREMENT
value of a MySQL table via
ALTER TABLE some_table AUTO_INCREMENT = 1000
However I need to set the AUTO_INCREMENT
upon its existing value (to fix M-M replication), something like:
ALTER TABLE some_table SET AUTO_INCREMENT = AUTO_INCREMENT + 1
which is not working
Well actually, I would like to run this query for all tables within a database. But actually this is not very crucial.
I could not find out a way to deal with this problem, except running the queries manually. Will you please suggest something or point me out to some ideas.
Thanks
Using:
...will reset the auto_increment value to be the next value based on the highest existing value in the auto_increment column.
To run this over all the tables, you'll need to use MySQL's dynamic SQL syntax called PreparedStatements because you can't supply the table name for an ALTER TABLE statement as a variable. You'll have to loop over the output from:
...running the ALTER TABLE statement above for each table.
I found this gist on github and it worked like a charm for me: https://gist.github.com/abhinavlal/4571478
The command:
If your DB requires a password, you unfortunately have to put that in the command for it to work. One work-around (still not great but works) is to put the password in a secure file. You can always delete the file after so the password doesn't stay in your command history:
In the below instructions you will need to replace everything that is in [brackets] with your correct value. BACKUP BEFORE ATTEMPTING.
If you can login to mysql as root through the command line then you could do the following to reset the auto_increment on all tables, first we will construct our queries which we want to run:
Make a database backup:
Login:
Set the group_concat_max_length to a higher value so our list of queries doesn't get truncated:
Create our list of queries by using the following:
Then you will receive a long string of mysql queries followed by a bunch of dashes. Copy the string of queries to your clipboard, it will look something similar to:
Change to the database you would like to run the command on:
Then paste the string that is on your clipboard and hit enter to run it. This should run the alter on every table in your database.
Messed up? Restore from your backup, be sure to logout of mysql before running the following (just type
exit;
to do so)I will not take responsibility for any damage cause by your use of any of these commands, use at your own risk.
Then copy-paste and run the output you get.
Reset mysql table auto increment was very easy, we can do it with single query, please see this http://webobserve.blogspot.com/2011/02/reset-mysql-table-autoincrement.html.
I have written below procedure change the database name and execute the procedure
Execute the procedure above using below line