mysql (5.1) > create table with name from a variable

Jakob Jingleheimer picture Jakob Jingleheimer · Sep 20, 2011 · Viewed 19.5k times · Source

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.

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.

@yyyy_mm resolves to 2020.

Answer

nos picture nos · Sep 20, 2011

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;