当前位置:网站首页>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 .
边栏推荐
- sectigo ov泛域名证书一年一千五百九十元好用吗
- KUKA子程序/函数怎么建立和使用方法
- Word2vec vector model of Wiki Chinese corpus based on deep learning
- 【现代信号处理第六次作业】
- It is the same that robots can win gold medals without maintenance and out of bounds
- Function calculation asynchronous task capability introduction - task trigger de duplication
- Bags of Binary Words for Fast Place Recognition in Image Sequenc
- LeetCode 每日一题——535. TinyURL 的加密与解密
- Multi mode concurrent implementation of tortoise and rabbit race in go language
- 6.26cf simulation game d: black and white questions
猜你喜欢

SpingMVC请求和响应

linux中mysql 1045错误如何解决
![[R language data science]: Text Mining (taking Trump's tweet data as an example)](/img/4f/09b9885915bee50fb40976a5002730.png)
[R language data science]: Text Mining (taking Trump's tweet data as an example)

ICML 2022 | 基于解耦梯度优化的可迁移模仿学习方法

NVIDIA安装最新显卡驱动

mysql支持外键吗

Why is informatization ≠ digitalization? Finally someone made it clear

Tencent cloud released orbit, an automated delivery and operation and maintenance product, to promote enterprise applications to be fully cloud native

Viewing splitchunks code segmentation from MPX resource construction optimization

如何创建虚拟形象
随机推荐
What are the project management systems suitable for small and medium-sized enterprises?
首批!腾讯云通过中国信通院政务协同平台解决方案能力评估
腾讯云发布自动化交付和运维产品Orbit,推动企业应用全面云原生化
c# 国内外ORM 框架 dapper efcore sqlsugar freesql hisql sqlserver数据常规插入测试性能对比
【R语言数据科学】:文本挖掘(以特朗普推文数据为例)
Shenzhen internal promotion | Shenzhen Institute of computing science recruits assistant machine learning Engineer (school recruitment)
External automatic (PLC start robot)
6.26cf simulation game d: black and white questions
R语言dplyr包filter函数通过组合逻辑(与逻辑)过滤dataframe数据中的数据、其中一个字段的内容等于指定向量中的其中一个,并且另外一个字段值大于某一阈值
mysql在linux中2003错误如何解决
Kotlin basic grammar
Multi mode concurrent implementation of tortoise and rabbit race in go language
[R language data science]: Text Mining (taking Trump's tweet data as an example)
Calibration of monocular camera and binocular camera with kalibr calibration tool
函数计算异步任务能力介绍 - 任务触发去重
How to use interrupt
底层内功修养
Interrupt怎么用
自学结构体(小甲鱼c语言)
An error is reported in the Flink SQL rownumber. Who has met him? How to solve it?