问题
I try to (re)set the auto_increment value to the value of a variable, but it fails:
CREATE TABLE test_table (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1;
SET @tmpvar = 12345;
ALTER TABLE test_table AUTO_INCREMENT=@tmpvar;
The last command fails with:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@tmpvar' at line 1
Is it not possible to set the AUTO_INCREMENT value like this? What are the alternatives? I need to set this value in a stored procedure that rotates log tables and I need the new table to start with values taken from some old table.
Addendum
The direct creation of the table with the correct auto increment intial value fails as well:
CREATE TABLE test_table (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=@tmpvar;
P.S. I found a related question here on So, but with no answer: Updating auto_increment value in an InnoDB table
EDIT corrected missing semicolon
回答1:
Try:
CREATE TABLE `test_table` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1;
SET @`tmpvar` := 12345;
SET @`stmt_alter` := CONCAT('ALTER TABLE `test_table` AUTO_INCREMENT = ', @`tmpvar`);
PREPARE `stmt` FROM @`stmt_alter`;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;
SQL Fiddle demo
UPDATE
You can use 13.5 SQL Syntax for Prepared Statements for 13.1.14 CREATE TABLE Syntax.
SET @`tmpvar` := 12345;
SET @`stmt_create` := CONCAT('CREATE TABLE `test_table` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=', @`tmpvar`);
PREPARE `stmt` FROM @`stmt_create`;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;
SQL Fiddle demo
来源:https://stackoverflow.com/questions/34267137/using-variable-in-setting-mysql-innodb-auto-increment-table-value