在设置mysql INNODB AUTO_INCREMENT表值时使用变量

时间:2015-12-14 12:32:02

标签: mysql stored-procedures auto-increment

我尝试(重新)将auto_increment值设置为变量的值,但它失败了:

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;

最后一个命令失败:

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

是否无法像这样设置AUTO_INCREMENT值?有哪些替代方案?我需要在一个旋转日志表的存储过程中设置此值,我需要新表以从一些旧表中获取的值开始。

附录

使用正确的自动增量初始值直接创建表也会失败:

CREATE TABLE test_table (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT, 
  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=@tmpvar;

P.S。我在这里找到了一个相关的问题,但没有答案:Updating auto_increment value in an InnoDB table

修改的 纠正缺失的分号

1 个答案:

答案 0 :(得分:2)

尝试:

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

<强>更新

您可以13.5 SQL Syntax for Prepared Statements使用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