2016-11-10 69 views
-1

可以說我想要做$table = 'datatables_demo';這樣的話我可以做select * from $table變量?我怎樣才能做到這一點?我可以聲明在mysql命令行

LOG低於

mysql> select * from datatables_demo;           +----+------------+-----------+-------------+--------+------------+--------+ 
| id | first_name | last_name | position | office | start_date | salary | 
+----+------------+-----------+-------------+--------+------------+--------+ 
| 1 | Tiger  | Nixon  | Accountant | Tokyo | 2016-11-08 | 320800 | 
| 2 | Garrett | Winters | Accountant2 | Tokyo | 2016-11-08 | 170750 | 
| 3 | Ashton  | Cox  | Accountant3 | Tokyo | 2016-11-08 | 86000 | 
| 4 | Cedric  | Kelly  | Accountant4 | Tokyo | 2016-11-08 | 433060 | 
| 5 | Tiger5  | Nixon  | Accountant | Tokyo | 2016-11-08 | 320800 | 
+----+------------+-----------+-------------+--------+------------+--------+ 
5 rows in set (0.00 sec) 

mysql> $table = 'datatables_demo'; 
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$table = 'datatables_demo'' at line 1 
mysql> table = 'datatables_demo'; 
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table = 'datatables_demo'' at line 1 
mysql> var table varchar2(20) 
    -> ; 
+1

的可能的複製[如何聲明在MySQL變量?(http://stackoverflow.com/questions/11754781/how-to-declare-a-variable- in-mysql) – csmckelvey

+0

那個笨蛋不會幫助解決這個問題。你需要一個存儲過程和一個concat和一個準備好的stmt在mysql中。總而言之,沒有太多投資回報的很多馬戲 – Drew

+0

不可能從命令行 – Rahul

回答

1

你應該使用PREPARE STATEMENT實現動態SQL語句。

告訴你一個例子

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64)) 
BEGIN 
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl); 
    PREPARE stmt FROM @s; 
    EXECUTE stmt; 
    DEALLOCATE PREPARE stmt; 
END 
// 
delimiter ; 
+0

爲什麼字符?那些輸入參數應該是varchar而不是 – Rahul

+0

tks我該如何將它應用到我的特定示例'select * from ; '? – HattrickNZ