当前位置:网站首页>The method of solving stored procedure table name passing through variable in mysql
The method of solving stored procedure table name passing through variable in mysql
2022-08-01 04:26:00 【live healthy and safe】
A problem description
In the stored procedure, simply use the set or declare statement to define the variable, and then directly use it as the sql table name is not enough, mysql will treat the variable name asas table name. The same is true in other sql databases.This was not possible before mysql5.0. After 5.0, a new statement was introduced to achieve a function similar to sp_executesql (only valid for procedure, function does not support dynamic query):
Two solutions
If we need to do the insert operation in the stored procedure, according to the table name passed in from outside.The code is as follows:
drop PROCEDURE if EXISTS p_sync_data;CREATE PROCEDURE `p_sync_data`(IN pa_table_name varchar(255))BEGINDECLARE 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); #Use the concat splicing string function to assign the sql of the copied table to the variable sql_create_tableset @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;# preprocessing tablePREPARE stmt FROM @sql_create_table;# execute sqlEXECUTE stmt USING @id,@cname,@kc,@fs;deallocate prepare stmt;-- insert into tb_kc_789 values(@id,@tname,@kc,@fs);end
Screenshot below
3,.execute statement
call p_sync_data("tb_kc");
commit;
4. Results data
边栏推荐
猜你喜欢
Input input box cursor automatically jumps to the last bug after the previous input
Valentine's Day Romantic 3D Photo Wall [with source code]
移动端页面秒开优化总结
IJCAI2022 | Hybrid Probabilistic Reasoning with Algebraic and Logical Constraints
干货!如何使用仪表构造SRv6-TE性能测试环境
时时刻刻保持敬畏之心
Flutter “Hello world“ 程代码
Visual Studio提供的 Command Prompt 到底有啥用
基于Arduino制作非接触式测温仪
TypeScript简化运行之ts-node
随机推荐
2022-07-31: Given a graph with n points and m directed edges, you can use magic to turn directed edges into undirected edges, such as directed edges from A to B, with a weight of 7.After casting the m
让你的 Lottie 支持文字区域内自动换行
PMP子过程定义总结
今日睡眠质量记录68分
干货!如何使用仪表构造SRv6-TE性能测试环境
typescript25-类型断言
PMP 项目资源管理
ICML2022 | Deep Dive into Permutation-Sensitive Graph Neural Networks
【无标题】
黑客到底可以厉害到什么程度?
7 行代码搞崩溃 B 站,原因令人唏嘘!
RSA主要攻击方法
Progressive Reconstruction of Visual Structure for Image Inpainting 论文笔记
How to write a high-quality digital good article recommendation
基于ProXmoX VE的虚拟化家庭服务器(篇一)—ProXmoX VE 安装及基础配置
button去除黑框
Excel做题记录——整数规划优化模型
【愚公系列】2022年07月 .NET架构班 085-微服务专题 Abp vNext微服务网关
Mysql中的数据类型和运算符
Introduction to the Elastic Stack