我尝试创建一个每天运行一次的过程,并存储更大表中的数据子集。该表的名称应使用CURDATE()动态创建。
DROP PROCEDURE daily_backup;
DELIMITER |
CREATE PROCEDURE daily_backup()
BEGIN
SET @tbl = CONCAT('items_data_', DATE_FORMAT(CURDATE(), '%Y%m%d'));
SET @s = CONCAT('DROP TABLE IF EXISTS ', @tbl);
PREPARE stmt FROM @s;
EXECUTE stmt;
@s = CONCAT('CREATE TABLE `', @tb1, '` (`id` int(11) NOT NULL,`up` mediumint(9) NOT NULL,`down` mediumint(9) NOT NULL) ENGINE=Archive');
PREPARE stmt FROM @s;
EXECUTE stmt;
SET @s = CONCAT('INSERT INTO ', @tbl, ' SELECT id,up,down FROM items;');
PREPARE stmt FROM @s;
EXECUTE stmt;
END
这些是结果
#1064-您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在'@s = CONCAT('CREATE TABLE`',@ tb1,'`(`id` int(11)NOT NULL,`up` mediumint( 9)'在第8行
编辑 //立即工作
DROP PROCEDURE daily_backup;
DELIMITER |
CREATE PROCEDURE daily_backup()
BEGIN
SET @tbl = CONCAT('items_data_', DATE_FORMAT(CURDATE(), '%Y%m%d'));
SET @s = CONCAT('DROP TABLE IF EXISTS ', @tbl);
PREPARE stmt FROM @s;
EXECUTE stmt;
SET @s = CONCAT('CREATE TABLE `', @tbl, '` (`id` int(11) NOT NULL,`up` mediumint(9) NOT NULL,`down` mediumint(9) NOT NULL) ENGINE=Archive');
PREPARE stmt FROM @s;
EXECUTE stmt;
SET @s = CONCAT('INSERT INTO ', @tbl, ' SELECT id,up,down FROM items;');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
答案 0 :(得分:2)
变量分配始终需要一个SET
命令:
SET @s = CONCAT('CREATE TABLE `', @tbl, '` (`id` int(11) NOT NULL,`up` mediumint(9) NOT NULL,`down` mediumint(9) NOT NULL) ENGINE=Archive');
请注意,您在此语句中有@tb1
,应该为@tbl
。
在您使用DEALLOCATE
一条准备好的语句(即
DEALLOCATE PREPARE stmt;
在EXECUTE stmt