当前位置:网站首页>What is the function of MySQL cursors
What is the function of MySQL cursors
2022-06-29 17:23:00 【Yisu cloud】
mysql What is the function of a cursor
Today I'd like to share with you mysql What is the function of the cursor , Detailed content , Clear logic , I believe most people still know too much about this knowledge , So share this article for your reference , I hope you will gain something after reading this article , Now let's take a look .
stay mysql in , Cursor has the function of pointer , It is mainly used to traverse the record result set returned by the query database , In order to carry out the corresponding operation . A cursor is actually a mechanism that can extract one record at a time from a result set that contains multiple data records . The essence of RDBMS is set oriented , stay MySQL There is no representation in the table that describes a single record in the table , Unless used WHERE Clause to restrict only one record to be selected ; So sometimes we must use the cursor to process the data of a single record .
The operating environment of this tutorial :windows7 System 、mysql8 edition 、Dell G3 The computer .
MySQL The cursor (Cursor)
A cursor is actually a mechanism that can extract one record at a time from a result set that contains multiple data records .
The cursor acts as a pointer .
Although the cursor can traverse all the rows in the result , But he only points to one line at a time .
The function of cursor is to traverse the records returned by query database , In order to carry out the corresponding operation .
The essence of RDBMS is set oriented , stay MySQL There is no representation in the table that describes a single record in the table , Unless used WHERE Clause to restrict only one record to be selected . So sometimes we must use the cursor to process the data of a single record .
Generally, data modification is performed by locating the cursor to a row of the result set .
Usage of cursors
1、 Declare a cursor : declare Cursor name CURSOR for table;( there table It can be any set you query out )
2、 Open defined cursor :open Cursor name ;
3、 Get the next row of data :FETCH Cursor name into testrangeid,versionid;
4、 Statements that need to be executed ( Additions and deletions ): It depends on the circumstances
5、 Release cursor :CLOSE Cursor name ;
notes :mysql The stored procedure must be followed by ; ending , The temporary fields used need to be declared before the cursor is defined .
example
- BEGIN -- Defining variables declare testrangeid BIGINT; declare versionid BIGINT; declare done int; -- Create cursors , And store data declare cur_test CURSOR for select id as testrangeid,version_id as versionid from tp_testrange; -- After the contents of the cursor are executed, the done Set to 1 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done=1; -- Open cursor open cur_test; -- Execute loop posLoop:LOOP -- Determine whether to end the loop IF done=1 THEN LEAVE posLoop; END IF; -- Take the value in the cursor FETCH cur_test into testrangeid,versionid; -- Perform an update operation update tp_data_execute set version_id=versionid where testrange_id = testrangeid; END LOOP posLoop; -- Release cursor CLOSE cur_test; END -
Example 2:
Now we're going to do a function with stored procedures , Statistics iphone What's the total stock of , And output the total to the console .
-- stay windows When writing stored procedures in the system , If needed declare Declare variables , You need to add this keyword , Otherwise, an error will be reported . delimiter // drop procedure if exists StatisticStore; CREATE PROCEDURE StatisticStore() BEGIN -- Create variables to receive cursor data declare c int; declare n varchar(20); -- Create a total variable declare total int default 0; -- Create an end flag variable declare done int default false; -- Create cursors declare cur cursor for select name,count from store where name = 'iphone'; -- Specifies the return value at the end of the cursor loop declare continue HANDLER for not found set done = true; -- Set initial value set total = 0; -- Open cursor open cur; -- Start looping through the data in the cursor read_loop:loop -- According to a piece of data that the cursor currently points to fetch cur into n,c; -- Determine whether the cursor's loop ends if done then leave read_loop; -- Jump out of the cursor loop end if; -- When getting a piece of data , take count Value to be accumulated , Here you can do whatever you want , set total = total + c; -- End cursor loop end loop; -- Close cursor close cur; -- Output results select total; END; -- Calling stored procedure call StatisticStore();
fetch Is to get the data row that the cursor currently points to , And point the pointer to the next line , Continuing to execute when the cursor has already pointed to the last row will cause cursor overflow .
Use loop When you cycle the cursor , He doesn't monitor the last data himself , Like the following code , It's going to create a dead cycle ;
read_loop:loop fetch cur into n,c; set total = total+c; end loop;
stay MySql in , Causes a cursor overflow mysql Predefined NOT FOUND error , So use the following code above to specify when to raise not found Define a... When it's wrong continue Events , Specifies to modify when this event occurs done The value of the variable .
declare continue HANDLER for not found set done = true;
So I added the following code in the loop :
-- Determine whether the cursor's loop ends if done then leave read_loop; -- Jump out of the cursor loop end if;
If done The value of is true, Just close the loop . Continue with the following code
Usage mode
There are three ways to use cursors :
The first is the above implementation , Use loop loop ;
The second way is as follows , Use while loop :
drop procedure if exists StatisticStore1; CREATE PROCEDURE StatisticStore1() BEGIN declare c int; declare n varchar(20); declare total int default 0; declare done int default false; declare cur cursor for select name,count from store where name = 'iphone'; declare continue HANDLER for not found set done = true; set total = 0; open cur; fetch cur into n,c; while(not done) do set total = total + c; fetch cur into n,c; end while; close cur; select total; END; call StatisticStore1();
The third way is to use repeat perform :
drop procedure if exists StatisticStore2; CREATE PROCEDURE StatisticStore2() BEGIN declare c int; declare n varchar(20); declare total int default 0; declare done int default false; declare cur cursor for select name,count from store where name = 'iphone'; declare continue HANDLER for not found set done = true; set total = 0; open cur; repeat fetch cur into n,c; if not done then set total = total + c; end if; until done end repeat; close cur; select total; END; call StatisticStore2();
Cursor nesting
stay mysql in , Every begin end The blocks are all independent scope Area , because MySql The same one error Can only be defined once , If there are multiple definitions, you will be prompted at compile time Duplicate handler declared in the same block.
drop procedure if exists StatisticStore3; CREATE PROCEDURE StatisticStore3() BEGIN declare _n varchar(20); declare done int default false; declare cur cursor for select name from store group by name; declare continue HANDLER for not found set done = true; open cur; read_loop:loop fetch cur into _n; if done then leave read_loop; end if; begin declare c int; declare n varchar(20); declare total int default 0; declare done int default false; declare cur cursor for select name,count from store where name = 'iphone'; declare continue HANDLER for not found set done = true; set total = 0; open cur; iphone_loop:loop fetch cur into n,c; if done then leave iphone_loop; end if; set total = total + c; end loop; close cur; select _n,n,total; end; begin declare c int; declare n varchar(20); declare total int default 0; declare done int default false; declare cur cursor for select name,count from store where name = 'android'; declare continue HANDLER for not found set done = true; set total = 0; open cur; android_loop:loop fetch cur into n,c; if done then leave android_loop; end if; set total = total + c; end loop; close cur; select _n,n,total; end; begin end; end loop; close cur; END; call StatisticStore3();
The above is to implement a nested loop , Of course, this example is far fetched . Just make do with it .
dynamic SQL
Mysql Support dynamic SQL The function of
set @sqlStr='select * from table where condition1 = ?'; prepare s1 for @sqlStr; -- If there are multiple arguments separated by commas execute s1 using @condition1; -- Release by hand , Or is it connection closed , server Automatic recovery deallocate prepare s1;
That's all “mysql What is the function of a cursor ” All the content of this article , Thank you for reading ! I believe you will gain a lot after reading this article , Xiaobian will update different knowledge for you every day , If you want to learn more , Please pay attention to the Yisu cloud industry information channel .
边栏推荐
- 毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
- C language practice ---- pointer string and linked list
- SLAM中的子图
- 2020版KALI安装教程
- Why is informatization ≠ digitalization? Finally someone made it clear
- 2022 software evaluator examination outline
- PCB板框的绘制——AD19
- 在线SQL转CSV工具
- 关于KALI使用xshell连接
- It is the same that robots can win gold medals without maintenance and out of bounds
猜你喜欢

深圳内推 | 深圳计算科学研究院招聘机器学习助理工程师(校招)

Redis 原理 - Sorted Set (ZSet)

Leetcode daily question - 535 Encryption and decryption of tinyurl

In depth analysis of Monai (I) data and transforms

【R语言数据科学】:文本挖掘(以特朗普推文数据为例)

SLAM中的子图

@Difference between component and @configuration

@Component与@Configuration区别

mysql查询视图命令是哪个

0 basic self-study STM32 (wildfire) - register lit LED
随机推荐
Interrupt怎么用
0基础自学STM32(野火)——使用寄存器点亮LED——GPIO功能框图讲解
mysql游标的作用是什么
LeetCode 每日一题——535. TinyURL 的加密与解密
Subgraphs in slam
序列检测器
Online text digit recognition list summation tool
Help MySQL data analysis with databend
PCB frame drawing - ad19
mysql查询视图命令是哪个
自学结构体(小甲鱼c语言)
mysql.sock的概念是什么
InheritableThreadLocal 在线程池中进行父子线程间消息传递出现消息丢失的解析
Word2vec vector model of Wiki Chinese corpus based on deep learning
What are the project management systems suitable for small and medium-sized enterprises?
C comparison of the performance of dapper efcore sqlsugar FreeSQL hisql sqlserver, an ORM framework at home and abroad
c# 国内外ORM 框架 dapper efcore sqlsugar freesql hisql sqlserver数据常规插入测试性能对比
深圳内推 | 深圳计算科学研究院招聘机器学习助理工程师(校招)
Viewing splitchunks code segmentation from MPX resource construction optimization
自定義HandlerInterceptor攔截器實現用戶鑒權