解决 mysql 存储过程查询数据方式是变量拼接表名的写法
需求:
用存储过程查询动态表名的数据
遇到问题:
查询语句 from后面不能直接用参数查询 MYSQL不支持直接使用变量做表名,会把参数名当做表名查询,报错
解决方法:
把查询语句和变量通过concat连接付给变量。通过执行变量来执行此语句
sql代码:
delimiter $$
drop procedure if exists productpricing $$ #如果此存储过程存在就删除
create procedure productpricing(IN activityCode varchar(20),IN `userId` int,IN `activityId` int)
begin
SET @STMT :=CONCAT("select p.id as longitude , p.visit_id as latitude from people_",activityCode," as p where p.id = 88 and p.visit_type = 3");
PREPARE STMT FROM @STMT;
EXECUTE STMT;
end;
$$
delimiter ;
执行存储过程:
CALL productpricing('visit',2,2);
结果显示: