Mysql

在儲存過程中使用變數

  • May 15, 2015

我想使用儲存的 pdocedure 動態創建一個元表,並將表前綴作為“in”參數傳遞,然後以某種方式建構最終表名。

我的程式碼如下所示:

SET @table_ = CONCAT(tablename, '_meta');
CREATE TABLE @table_ (name varchar(50), value varchar(50)) ENGINE=MyISAM;

tablenamein 參數在哪裡(如 varchar(50) utf-8)

但我總是面臨這個錯誤:

‘CREATE TABLE @table_ (name varchar(50), value varchar(50)) ENGINE=MyISAM’ 附近的語法錯誤

我錯過了什麼嗎?有人有提示嗎?

您可以為此使用準備語句,並且還需要為該過程設置一個分隔符,例如

delimiter //

create procedure table_create (in tablename varchar(100))
begin
set @table_ = concat(tablename, '_meta');
set @qry = concat("create table ",@table_,"(name varchar(50), value varchar(50)) ENGINE=MyISAM;");
prepare stmt from @qry;
execute stmt;    
end;//

delimiter ;

這是mysql中的一個測試案例

mysql> delimiter //
mysql> 
mysql> create procedure table_create (in tablename varchar(100))
   -> begin
   ->  set @table_ = concat(tablename, '_meta');
   ->  set @qry = concat("create table ",@table_,"(name varchar(50), value varchar(50)) ENGINE=MyISAM;");
   ->  prepare stmt from @qry;
   ->  execute stmt;    
   -> end;//
Query OK, 0 rows affected (0.00 sec)

mysql> 
mysql> delimiter ;
mysql> call table_create('test');
Query OK, 0 rows affected (0.08 sec)

mysql> describe test_meta ;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| name  | varchar(50) | YES  |     | NULL    |       |
| value | varchar(50) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

引用自:https://dba.stackexchange.com/questions/101594