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
.
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 .
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With