当前位置:网站首页>mysql中解决存储过程表名通过变量传递的方法
mysql中解决存储过程表名通过变量传递的方法
2022-08-01 04:20:00 【健康平安的活着】
一 问题描述
在存储过程中,简单的用set或者declare语句定义变量,然后直接作为sql的表名是不行的,mysql会把变量名当作表名。在其他的sql 数据库中也是如此。这在 mysql5.0之前是不行的,5.0之后引入了一个全新的语句,可以达到类似sp_executesql的功能(仅对procedure有效,function不支持动态查询):
二 解决办法
如果我们需要在存储过程中,根据外面传进来的表名,做插入操作。代码如下:
drop PROCEDURE if EXISTS p_sync_data;
CREATE PROCEDURE `p_sync_data`(
IN pa_table_name varchar(255)
)
BEGIN
DECLARE n int(10);
set @currMonth=MONTH(CURDATE());
set @[email protected];
if @a=1 or @a=2 or @a=3 then set n=123;
elseif @a=4 or @a=5 or @a=6 then set n=456;
elseif @a=7 or @a=8 or @a=9 then set n=789;
else set n=101112;
end if;
set @tbName=concat(pa_table_name,'_',n); #利用concat拼接字符串函数,将复制表的sql赋值到变量sql_create_table
set @id=7;
set @cname="zhangsan";
set @kc="yingyu";
set @fs=90;
set @sql_create_table = concat('insert into ',@tbName," set `id`=?,`name`=?,`kecheng`=?,`fenshu`=?;");
select @sql_create_table;
# 预处理建表
PREPARE stmt FROM @sql_create_table;
# 执行sql
EXECUTE stmt USING @id,@cname,@kc,@fs;
deallocate prepare stmt;
-- insert into tb_kc_789 values(@id,@tname,@kc,@fs);
end截图如下

3,。执行语句
call p_sync_data("tb_kc");
commit;
4.结果数据

边栏推荐
- Simulation of Active anti-islanding-AFD Active Anti-islanding Model Based on Simulink
- Mysql中的数据类型和运算符
- [Search topic] After reading the inevitable BFS solution to the shortest path problem
- 这里有110+公开的专业数据集
- scheduleWithFixedDelay和scheduleAtFixedRate的区别
- Message Queuing Message Storage Design (Architecture Camp Module 8 Jobs)
- 解决ffmpeg使用screen-capture-recorder录屏,有屏幕缩放的情况下录不全的问题
- 时时刻刻保持敬畏之心
- 开源许可证 GPL、BSD、MIT、Mozilla、Apache和LGPL的区别
- PMP 项目沟通管理
猜你喜欢

Four implementations of
batch insert: have you really got it? ![[kali-information collection] enumeration - DNS enumeration: DNSenum, fierce](/img/97/bbe7c2af0ff8bcb5222b9105d80c73.png)
[kali-information collection] enumeration - DNS enumeration: DNSenum, fierce

Mysql基础篇(Mysql数据类型)

Step by step hand tearing carousel Figure 3 (nanny level tutorial)

使用ts-node报错

MySQL4

TypeScript simplifies running ts-node

Error using ts-node

这里有110+公开的专业数据集

简单易用的任务队列-beanstalkd
随机推荐
深圳某游戏研发公司给每个工位都装监控,网友:堪比坐牢!
7月编程排行榜来啦!这次有何新变化?
[SemiDrive source code analysis] series article link summary (full)
6-23漏洞利用-postgresql代码执行利用
数组问题之《两数之和》以及《三数之和 》
【无标题】
Excel做题记录——整数规划优化模型
基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置
Hackers can how bad to what degree?
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
出现Command ‘vim‘ is available in the following places,vim: command not found等解决方法
Software Testing Weekly (Issue 82): In fact, all those who are entangled in making choices already have the answer in their hearts, and consultation is just to get the choice that they prefer.
认真对待每一个时刻
移动端页面秒开优化总结
MySQL4
Software Testing Interview (3)
Message queue MySQL table for storing message data
Input输入框光标在前输入后自动跳到最后面的bug
简单易用的任务队列-beanstalkd
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints