MySQL存储过程使用动态表名

MySQL默认不支持表名作为变量名。

1)案例说明

若有一下存储过程:

drop procedure if exists selectByTableName;
create procedure selectByTableName(in tableName varchar(50))
begin
    select * from tableName;
end;

在进行调用时会报错:

call selectByTableName('user')
> 1146 - Table 'db2020.tablename' doesn't exist
> 时间: 0s

原因是它把变量tableName作为了表名,并不是把传入的值作为表名。

2)解决方案

解决方法是使用concat函数,然后用预处理语句传入动态表名来执行sql,对于增删改查都适用。

将上述的存储过程修改如下:

drop procedure if exists selectByTableName;
create procedure selectByTableName(in tableName varchar(50))
begin
    #定义语句
    set @stmt = concat('select * from ',tableName);
    #预定义sql语句,从用户变量中获取
    prepare stmt from @stmt;
    #执行sql语句
    execute stmt;
    #释放资源,后续还可以使用
    deallocate prepare stmt;
end;

再调用时就能正常查询出结果了。在预处理语句中,使用了用户变量,变量名是自定义的。

就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
原文地址:https://www.cnblogs.com/zys2019/p/15171722.html