gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:19:10 25 4
gpt4 key购买 nike

我尝试(重新)将 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;

附言我在 So 上发现了一个相关问题,但没有答案:Updating auto_increment value in an InnoDB table

编辑更正了丢失的分号

最佳答案

尝试:

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

关于mysql - 在设置 mysql INNODB AUTO_INCREMENT 表值时使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34267137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com