SQL语句中的动态表名

14

我正在尝试执行类似于这样的 MySQL 查询

SET @id := '47';
SET @table := @id+'_2013_2014_voucher';
SELECT * FROM @table;
Delete FROM @table where id=@id

它显示了这样的错误

[Err] 1064 - 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' at line 1

我该如何解决?


请看以下内容:http://dev.mysql.com/doc/refman/5.0/en/user-variables.html - cpoDesign
3个回答

17

在查询中使用动态表名最好使用Prepared Statements,此外,在MySQL中连接字符串的函数是concat

SET @id := '47';
SET @table := concat(@id,'_2013_2014_voucher');
set @qry1:= concat('select * from ',@table);
prepare stmt from @qry1 ;
execute stmt ;

你也可以像删除查询一样执行它


10

对于动态表名,您需要使用准备好的语句。准备好的语句支持参数,但不能用于表名。

此外,要将字符串拼接在一起,您必须使用CONCAT()

噢,而且您必须在存储过程中完成所有这些操作。

创建一个如下所示:

DELIMITER $$
CREATE PROCEDURE sp_exec_dynStmt()
BEGIN
SET @id := 47; /*The single-quotes made it a string, that's not necessary*/
SET @table := CONCAT(@id, '_2013_2014_voucher');

SET @sql := CONCAT('SELECT * FROM ', @table, ';');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @sql = CONCAT('DELETE FROM ', @table, ' WHERE id = ?;'); /*The id can be a parameter, but not the table name*/
PREPARE stmt FROM @sql;
EXECUTE stmt USING @id; 
END $$
DELIMITER ;

然后像这样执行它:

CALL sp_exec_dynStmt();

0

尝试用以下代码替换该行

SET @table = '`' + @id+'_2013_2014_voucher`';

通常我会这样声明变量: SET @id = '47';(不带冒号)
在使用SET时,你应该只使用:,而在SELECT中分配变量时则应该使用:=

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接