我需要多次在查询中使用表名。为了避免重复,我想将名称存储到User-Defined Variable中。
此查询出了什么问题?
SET @tableName := 'de-Table'
SELECT * FROM @tableName;
在MariaDB中,错误是隐秘的,并且(照常)完全没有帮助:
/* SQL Error (1064): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM @tableName' at line 3 */
提前谢谢
答案 0 :(得分:2)
如果要将变量作为表名,则需要使用动态MySQL。如果直接从MySQL执行以下操作,则应该可以使用以下代码:
SET @tableName = 'de-Table';
SET @query = CONCAT('SELECT * FROM ', @tableName);
PREPARE stmt FROM @query;
EXECUTE stmt;