mysql 表名作为存储过程变量
mysql默认不支持表名作为变量名,如下所示
delimiter $$ DROP procedure IF EXISTS getDataByDbName $$ CREATE procedure getDataByDbName(in dbName VARCHAR(20)) BEGIN select * from dbName; end$$ delimiter;
当运行会报错
[SQL] call getDataByDbName("xxx"); [Err] 1146 - Table 'xxx.dbname' doesn't exist
这里需要用到mysql的一个字符串拼接函数CONCAT(),使用用户变量得到结果,然后输出即可
delimiter $$ DROP procedure IF EXISTS getDataByDbName $$ CREATE procedure getDataByDbName(in dbName VARCHAR(20)) BEGIN SET @STMT =CONCAT("SELECT * from ",dbName,";"); PREPARE STMT FROM @STMT; EXECUTE STMT; end$$ delimiter;