• 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;

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

    就是这么简单,你学废了吗?感觉有用的话,给笔者点个赞吧 !
  • 相关阅读:
    [背包]JZOJ 3232 【佛山市选2013】排列
    内核空间、用户空间、虚拟地址
    进程与线程的概念
    Python中字符串颜色
    socket编程
    模块与包
    常用模块
    面向对象进阶
    面向对象编程
    函数式编程
  • 原文地址:https://www.cnblogs.com/zys2019/p/15171722.html
Copyright © 2020-2023  润新知