sql语句中的动态表名

时间:2014-12-18 08:58:02

标签: mysql

我正在尝试像这样执行一个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

我如何实现这一目标?

3 个答案:

答案 0 :(得分:9)

Prepared Staments 中,查询中动态表名称的使用效果最佳, 在mysql中也可以连接函数concat

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

您也可以为删除查询执行此操作

答案 1 :(得分:5)

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

另外,为了将字符串放在一起,您必须使用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();

答案 2 :(得分:0)

尝试使用

更改该行
SET @table = '`' + @id+'_2013_2014_voucher`';

通常我以这种方式声明变量

SET @id = '47';(不含:

您应该只使用:SET:=分配SELECT

中的变量
相关问题