如何在select语句中将变量值作为表名获取

时间:2013-02-12 08:59:43

标签: mysql stored-procedures

SET Project_List_val=CONCAT(Project_Number_val,'_List');
Insert Into test (Manthan_Panel_Id) select Manthan_Panel_Id from Project_List_val where Project_Number_val='9';

在insert语句中有一个名为“Project_List_val”的变量,它由在上一步中合并的表名组成。此语句不将变量的内容作为表名,而是将“Project_List_val”作为表名并给出表未找到错误。

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

默认您无法参数化表名和列名,因此您需要为其创建动态SQL

SET @Project_List_val = CONCAT(Project_Number_val, '_List');
SET @projNum = 9;
SET @sql = CONCAT(' INSERT INTO test (Manthan_Panel_Id)
                    SELECT Manthan_Panel_Id 
                    FROM ', @Project_List_val, ' 
                    WHERE Project_Number_val = ?');

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