简体   繁体   中英

Using variable in setting mysql INNODB AUTO_INCREMENT table value

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;

PS I found a related question here on So, but with no answer: Updating auto_increment value in an InnoDB table

EDIT corrected missing semicolon

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM