创建一个包含日期名称的表

时间:2013-06-14 10:19:11

标签: mysql database stored-procedures

我正在编写一个备份表的简单程序 -

CREATE PROCEDURE daily_backup()
BEGIN
   DECLARE given_date VARCHAR(25);
   SET given_date = now(); 

   CREATE TABLE given_date LIKE db1.table1;
   INSERT INTO given_date SELECT * FROM db1.table1;


END

但它创建了一个名为given_date的表。我想创建一个日期为名称的表。怎么做?

2 个答案:

答案 0 :(得分:2)

生成创建语句,准备如下: -

set @given_date = now();
SET @sql = CONCAT("CREATE TABLE ",@given_date," as SELECT * FROM db1.table1");
PREPARE stmt from @sql;
EXECUTE stmt;

ps: - 表格名称应根据to this.

有效

答案 1 :(得分:0)

试试这个

DELIMITER |
CREATE PROCEDURE daily_backup()
BEGIN
  SET @s = CONCAT('CREATE TABLE bak_', DATE_FORMAT(CURDATE(), '%Y%m%d'), ' SELECT * FROM table1');
  PREPARE stmt FROM @s;
  EXECUTE stmt;
END
|
DELIMITER ;

更新:您可以让它一天多次运行

DROP PROCEDURE daily_backup;
DELIMITER |
CREATE PROCEDURE daily_backup()
BEGIN
  SET @tbl = DATE_FORMAT(CURDATE(), '%Y%m%d');
  SET @s = CONCAT('DROP TABLE IF EXISTS bak_', @tbl);
  PREPARE stmt FROM @s;
  EXECUTE stmt;

  SET @s = CONCAT('CREATE TABLE bak_', @tbl, ' SELECT * FROM table1');
  PREPARE stmt FROM @s;
  EXECUTE stmt;
END
|
DELIMITER ;

这是 SQLFiddle 演示