前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >MySQL 存储过程中使用游标中使用临时表可以替代数组效果

MySQL 存储过程中使用游标中使用临时表可以替代数组效果

作者头像
星哥玩云
发布2022-08-13 17:22:25
发布2022-08-13 17:22:25
1.5K0
举报
文章被收录于专栏:开源部署开源部署

MySQL不支持数组。但有时候需要组合几张表的数据,在存储过程中,经过比较复杂的运算获取结果直接输出给调用方,比如符合条件的几张表的某些字段的组合计算,MySQL临时表可以解决这个问题.临时表:只有在当前连接情况下, TEMPORARY 表才是可见的。当连接关闭时, TEMPORARY 表被自动取消。必须拥有 create temporary table 权限,才能创建临时表。可以通过指定 engine = memory; 来指定创建内存临时表。

先建立要用的数据表及数据:

drop table if exists  person; create table `person` (   `id` int(11)primary key NOT NULL DEFAULT '0',   `age` int(11) DEFAULT NULL,   `name` varchar(225) not null ) engine=innodb default charset=utf8; insert into person values(1,1,'zhangshan'),(2,2,'lisi'),(3,3,'lst'),(4,4,'jon'),(5,5,'test');

临时表支持主键、索引指定。在连接非临时表查询可以利用指定主键或索引来提升性能。存储过程语句及游标和临时表综合实例:

drop procedure if exists sp_test_tt; -- 判断存储过程函数是否存在如果是删除 delimiter ;; create procedure  sp_test_tt()  begin          create temporary table if not exists tmp  -- 如果表已存在,则使用关键词 if not exists 可以防止发生错误         (            id varchar(255) ,            name varchar(50),            age varchar(500)         ) engine = memory;          begin          declare ids int; -- 接受查询变量         declare names varchar(225); -- 接受查询变量         declare done int default false; -- 跳出标识         declare ages int(11); -- 接受查询变量         declare cur cursor for select id from person; -- 声明游标         declare continue handler for not FOUND set done = true; -- 循环结束设置跳出标识         open cur; -- 开始游标         LOOP_LABLE:loop -- 循环             FETCH cur INTO ids;             select name into names from person where id=ids;             select age into ages from person where id=ids;             insert into tmp(id,name,age) value(ids,names,ages);             if done THEN  -- 判断是否继续循环如果done等于true离开循环                 LEAVE LOOP_LABLE; -- 离开循环             END IF;             end LOOP; -- 结束循环         CLOSE cur; -- 关闭游标     select * from tmp; -- 查询临时表         end;          truncate TABLE tmp;  -- 使用 truncate TABLE 的方式来提升性能 end;  ;; delimiter ;;

执行存储过程:

call sp_test_tt();

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档