mysql(5.1)>使用变量名创建表

时间:2021-03-26 00:41:21

I'm trying to create a table with a name based on the current year and month(2011-09), but MySQL doesn't seem to like this.

我正在尝试创建一个基于当前年份和月份(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  |
+-----------+

If I do CREATE TABLE; without the ticks around @yyyy_mm, I get a generic syntax error.

如果我做CREATE TABLE;没有@yyyy_mm周围的刻度,我得到一般语法错误。

@yyyy_mm resolves to 2020.

@yyyy_mm结算到2020年。

2 个解决方案

#1


25  

You should be able to do something like this:

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

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


6  

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;

#1


25  

You should be able to do something like this:

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

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


6  

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;