当前位置:网站首页>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.结果数据
边栏推荐
猜你喜欢
Open source project site must-have & communication area function
对无限debugger的一种处理方式
MySQL3
JS new fun(); class and instance JS is based on object language Can only act as a class by writing constructors
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.
【无标题】
Error using ts-node
故乡的素描画
The 16th day of the special assault version of the sword offer
怀念故乡的月亮
随机推荐
Open source project site must-have & communication area function
FFmpeg 搭建本地屏幕录制环境
软件测试周刊(第82期):其实所有纠结做选择的人心里早就有了答案,咨询只是想得到内心所倾向的选择。
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
罗技鼠标体验记录
软件测试面试(三)
leetcode:126. Word Solitaire II
Game Theory (Depu) and Sun Tzu's Art of War (42/100)
项目风险管理必备内容总结
预言机简介
The Flow Of Percona Toolkit pt-table-checksum
基于STM32设计的UNO卡牌游戏(双人、多人对战)
动态规划 01背包
typescript27-枚举类型呢
Dart 命名参数语法
test
PMP 相关方管理必背总结
Summary of mobile page optimization in seconds
How to write a high-quality digital good article recommendation
Interview Blitz 69: Is TCP Reliable?Why?