当前位置:网站首页>[MySQL] basic use of cursor
[MySQL] basic use of cursor
2022-07-06 20:57:00 【Charming】
List of articles
1. What is a cursor ( Or the cursor )
Although it can be filtered by
WHEREandHAVING, Or a keyword that limits the return recordLIMITReturn a record , however , But it can't be like a pointer in the result set , Position a record forward 、 Position a record backward , Or is itRandomly locate a record, And process the recorded data .This is the time , You can use a cursor . The cursor , It provides a flexible operation mode , Be able to locate each record in the result set , A data structure that operates on the data in the pointed record . Cursor let SQL This set oriented language has the ability of process oriented development .
stay SQL in , A cursor is a temporary database object , Can point to the data row pointer stored in the database table . Here's the cursor
Acts as a pointer, You can manipulate data rows by manipulating cursors .MySQL Cursors can be used in stored procedures and functions .
such as , The query employees The salary in the data sheet is higher than 15000 What are your employees :
SELECT employee_id,last_name,salary FROM employees
WHERE salary > 15000;

Here, you can operate data rows through cursors , As shown in the figure, the line where the cursor is located is “108” The record of , You can also scroll the cursor on the result set , Point to any row in the result set .
2. Using cursor steps
The cursor must be declared before the handler is declared , And variables and conditions must also be declared before declaring cursors or handlers .
If you want to use a cursor , It usually takes four steps . Different DBMS in , The syntax for using cursors may be slightly different .
First step , declare cursor
stay MySQL in , Use DECLARE Keyword to declare the cursor , The basic form of its grammar is as follows :
DECLARE cursor_name CURSOR FOR select_statement;
This grammar applies to MySQL,SQL Server,DB2 and MariaDB. If it is to use Oracle perhaps PostgreSQL, Need to be written :
DECLARE cursor_name CURSOR IS select_statement;
To use SELECT Statement to get the data result set , At this time, the traversal of the data has not started , here select_statement It stands for SELECT sentence , Returns a result set used to create the cursor .
such as :
DECLARE cur_emp CURSOR FOR
SELECT employee_id,salary FROM employees;
DECLARE cursor_fruit CURSOR FOR
SELECT f_name, f_price FROM fruits ;
The second step , Open cursor
The syntax for opening a cursor is as follows :
OPEN cursor_name
When we define the cursor , If you want to use a cursor , The cursor must be opened first . When opening the cursor SELECT The query result set of the statement will be sent to the cursor workspace , For the following cursor Read one by one Prepare the records in the result set .
OPEN cur_emp;
The third step , Use cursors ( Get data from cursor )
The grammar is as follows :
FETCH cursor_name INTO var_name [, var_name] ...
The function of this sentence is to use cursor_name Use this cursor to read the current row , And save the data to var_name In this variable , The cursor pointer points to the next line . If the data row read by the cursor has multiple column names , It's in INTO Assign a value to multiple variable names after the keyword .
Be careful :var_name The cursor must be defined before it is declared .
FETCH cur_emp INTO emp_id, emp_sal ;
Be careful : The number of fields in the query result set of the cursor , Must follow INTO The following variables are the same , otherwise , When the stored procedure executes ,MySQL It will give you an error .
Step four , Close cursor
CLOSE cursor_name
Yes OPEN There will be CLOSE, That is, open and close the cursor . Close the cursor after using it . Because the cursor will Occupy system resources , If you don't close it in time , The cursor remains until the end of the stored procedure , Affect the efficiency of system operation . And closing the cursor , The system resources occupied by the cursor will be released .
After closing the cursor , You can no longer retrieve the data rows in the query results , If you need to retrieve, you can only open the cursor again .
CLOSE cur_emp;
3. give an example
- Create stored procedure “
get_count_by_limit_total_salary()”, StatementINParameterslimit_total_salary,DOUBLE type ; StatementOUTParameterstotal_count,INTtype . The function can accumulate the salary values of several employees with the highest salary , Until the total salary reacheslimit_total_salaryThe value of the parameter , Return the accumulated number of people tototal_count.
DELIMITER //
CREATE PROCEDURE get_count_by_limit_total_salary(IN limit_total_salary DOUBLE,OUT total_count INT)
BEGIN
DECLARE sum_salary DOUBLE DEFAULT 0; # Record the accumulated total salary
DECLARE cursor_salary DOUBLE DEFAULT 0; # Record a salary value
DECLARE emp_count INT DEFAULT 0; # Record the number of cycles
# Define cursors
DECLARE emp_cursor CURSOR FOR SELECT salary FROM employees ORDER BY salary DESC;
# Open cursor
OPEN emp_cursor;
REPEAT
# Use cursors ( Get data from cursor )
FETCH emp_cursor INTO cursor_salary;
SET sum_salary = sum_salary + cursor_salary;
SET emp_count = emp_count + 1;
UNTIL sum_salary >= limit_total_salary
END REPEAT;
SET total_count = emp_count;
# Close cursor
CLOSE emp_cursor;
END //
DELIMITER ;
- Inquire about How many individuals' wages are taken online more than 20w
# call
CALL get_count_by_limit_total_salary(200000,@total_count);
SELECT @total_count;

4. Summary
The cursor is MySQL An important function of , by
Read one by oneThe data in the result set , Provides the perfect solution . Compared with implementing the same function at the application level , Cursors can be used in stored programs , Efficient , The program is also more concise .But it also brings some performance problems , For example, in the process of using cursors , Data rows will be
Lock, In this way, when there is a large amount of business concurrency , It will not only affect the efficiency between businesses , WillConsume system resources, Cause insufficient memory , This is because cursors are processed in memory .Suggest : The habit of closing after use , This can improve the overall efficiency of the system .
边栏推荐
- 看过很多教程,却依然写不好一个程序,怎么破?
- 2022 refrigeration and air conditioning equipment installation and repair examination contents and new version of refrigeration and air conditioning equipment installation and repair examination quest
- Redis insert data garbled solution
- Intel 48 core new Xeon run point exposure: unexpected results against AMD zen3 in 3D cache
- 【DSP】【第一篇】开始DSP学习
- Simple continuous viewing PTA
- None of the strongest kings in the monitoring industry!
- Function optimization and arrow function of ES6
- Manifest of SAP ui5 framework json
- What is the problem with the SQL group by statement
猜你喜欢

Pycharm remote execution

SAP Fiori应用索引大全工具和 SAP Fiori Tools 的使用介绍

OAI 5g nr+usrp b210 installation and construction

知识图谱之实体对齐二

拼多多败诉,砍价始终差0.9%一案宣判;微信内测同一手机号可注册两个账号功能;2022年度菲尔兹奖公布|极客头条

Implementation of packaging video into MP4 format and storing it in TF Card

Comprehensive evaluation and recommendation of the most comprehensive knowledge base management tools in the whole network: flowus, baklib, jiandaoyun, ones wiki, pingcode, seed, mebox, Yifang cloud,

OLED屏幕的使用
![[weekly pit] calculate the sum of primes within 100 + [answer] output triangle](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[weekly pit] calculate the sum of primes within 100 + [answer] output triangle

请问sql group by 语句问题
随机推荐
性能测试过程和计划
Taylor series fast Fourier transform (FFT)
[200 opencv routines] 220 Mosaic the image
【每周一坑】计算100以内质数之和 +【解答】输出三角形
Kubernetes learning summary (20) -- what is the relationship between kubernetes and microservices and containers?
SAP UI5 框架的 manifest.json
Huawei device command
面试官:Redis中有序集合的内部实现方式是什么?
2022 Guangdong Provincial Safety Officer C certificate third batch (full-time safety production management personnel) simulation examination and Guangdong Provincial Safety Officer C certificate third
【mysql】游标的基本使用
快过年了,心也懒了
Yyds dry goods count re comb this of arrow function
Laravel笔记-自定义登录中新增登录5次失败锁账户功能(提高系统安全性)
Simple continuous viewing PTA
硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件
Manifest of SAP ui5 framework json
R language visualizes the relationship between more than two classification (category) variables, uses mosaic function in VCD package to create mosaic plots, and visualizes the relationship between tw
[weekly pit] output triangle
Le langage r visualise les relations entre plus de deux variables de classification (catégories), crée des plots Mosaiques en utilisant la fonction Mosaic dans le paquet VCD, et visualise les relation
基于STM32单片机设计的红外测温仪(带人脸检测)