我可以声明在mysql命令行
问题描述:
可以说我想要做$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)
-> ;
答
你应该使用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
的可能的复制[如何声明在MySQL变量?(http://*.com/questions/11754781/how-to-declare-a-variable- in-mysql) – csmckelvey
那个笨蛋不会帮助解决这个问题。你需要一个存储过程和一个concat和一个准备好的stmt在mysql中。总而言之,没有太多投资回报的很多马戏 – Drew
不可能从命令行 – Rahul