2011-09-20 47 views
11

我試圖創建一個基於當前年份和月份(2011-09)名稱的表,但MySQL似乎並不喜歡這樣。mysql(5.1)>從變量名稱創建表

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

+0

標識符是不變量。變量不是標識符。這需要使用「動態SQL」 - 它與我一起工作過的所有數據庫都很糟糕。 – 2011-09-20 17:25:46

+0

請參閱http://stackoverflow.com/questions/190776/how-to-have-dynamic-sql-in-mysql-stored-procedure和http://stackoverflow.com/questions/929244/mysql-create-table- with-dynamic-database-name和http://stackoverflow.com/questions/5530755/mysql-variables-storing-database-name – 2011-09-20 17:27:16

回答

24

你應該能夠做這樣的事情:

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; 
+0

nos&@nick:sweet!謝謝! – jacob

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;