如何使用Mysql过程和Date()创建存档表

时间:2019-04-20 01:58:24

标签: mysql date procedure archive

我尝试创建一个每天运行一次的过程,并存储更大表中的数据子集。该表的名称应使用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

1 个答案:

答案 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

之后