简体   繁体   English

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

[英]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: 我尝试将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;

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? 这样不能设置AUTO_INCREMENT值吗? 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 PS我在So上找到了一个相关的问题,但没有答案: 更新InnoDB表中的auto_increment值

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 SQL Fiddle演示

UPDATE UPDATE

You can use 13.5 SQL Syntax for Prepared Statements for 13.1.14 CREATE TABLE Syntax . 您可以对13.1.14 CREATE TABLE语法的预 准备语句使用13.5 SQL 语法

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 SQL Fiddle演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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