【问题标题】:mysql (5.1) > create table with name from a variablemysql (5.1) > 用变量名创建表
【发布时间】:2011-11-21 07:03:52
【问题描述】:

我正在尝试创建一个名称基于当前年份和月份的表 (2011-09),但 MySQL 似乎不喜欢这样。

SET @yyyy_mm=Year(NOW())+'-'+Month(NOW());
CREATE TABLE `survey`.`@yyyy_mm` LIKE `survey`.`interim`;
SHOW TABLES IN `survey`;

+-----------+
| interim   |
+-----------+
| @yyyy_mm  |
+-----------+

如果我在CREATE TABLE; 周围没有标记@yyyy_mm,则会收到一般语法错误。

@yyyy_mm 解析为 2020

【问题讨论】:

标签: mysql variables dynamic tablename


【解决方案1】:

你应该可以做这样的事情:

SET @yyyy_mm=DATE_FORMAT(now(),'%Y-%m');
SET @c = CONCAT('CREATE TABLE `survey`.`',@yyyy_mm, '` LIKE `survey`.`interim`');
PREPARE stmt from @c;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

【讨论】:

    【解决方案2】:
    set @yyyy_mm=concat(year(now()),'-',month(now()));
    set @str = concat('create table survery.`', @yyyy_mm,'` like survey.interim;');
    prepare stmt from @str;
    execute stmt;
    deallocate prepare stmt;
    

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-04
      • 1970-01-01
      相关资源
      最近更新 更多