Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 465
Jakob Jingleheimer Avatar asked Sep 20 '11 17:09

Jakob Jingleheimer


People also ask

How do you create a new table from a SELECT query?

You can create one table from another by adding a SELECT statement at the end of the CREATE TABLE statement: CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl; MySQL creates new columns for all elements in the SELECT .

How can you create a new table with existing data from another table?

A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. The new table has the same column definitions. All columns or specific columns can be selected.


1 Answers

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;
like image 84
nos Avatar answered Sep 22 '22 20:09

nos