当前位置:网站首页>[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 .
边栏推荐
- 动态切换数据源
- Swagger UI教程 API 文档神器
- 'class file has wrong version 52.0, should be 50.0' - class file has wrong version 52.0, should be 50.0
- [weekly pit] positive integer factorization prime factor + [solution] calculate the sum of prime numbers within 100
- Pinduoduo lost the lawsuit, and the case of bargain price difference of 0.9% was sentenced; Wechat internal test, the same mobile phone number can register two account functions; 2022 fields Awards an
- Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
- Introduction to the use of SAP Fiori application index tool and SAP Fiori tools
- [diy] self designed Microsoft makecode arcade, official open source software and hardware
- 【mysql】游标的基本使用
- Trends of "software" in robotics Engineering
猜你喜欢

Intel 48 core new Xeon run point exposure: unexpected results against AMD zen3 in 3D cache

Use of OLED screen
![[weekly pit] output triangle](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[weekly pit] output triangle

新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
![[200 opencv routines] 220 Mosaic the image](/img/75/0293e10ad6de7ed86df4cacbd79b54.png)
[200 opencv routines] 220 Mosaic the image

use. Net analysis Net talent challenge participation

1_ Introduction to go language

请问sql group by 语句问题

Opencv learning example code 3.2.3 image binarization

What programming do children learn?
随机推荐
1500万员工轻松管理,云原生数据库GaussDB让HR办公更高效
Gui Gui programming (XIII) - event handling
2022 nurse (primary) examination questions and new nurse (primary) examination questions
Kubernetes learning summary (20) -- what is the relationship between kubernetes and microservices and containers?
Web开发小妙招:巧用ThreadLocal规避层层传值
Activiti global process monitors activitieventlistener to monitor different types of events, which is very convenient without configuring task monitoring in acitivit
OAI 5g nr+usrp b210 installation and construction
Rhcsa Road
Yyds dry goods count re comb this of arrow function
Deployment of external server area and dual machine hot standby of firewall Foundation
Minimum cut edge set of undirected graph
[weekly pit] calculate the sum of primes within 100 + [answer] output triangle
Recyclerview GridLayout bisects the middle blank area
[diy] self designed Microsoft makecode arcade, official open source software and hardware
Taylor series fast Fourier transform (FFT)
C language operators
正则表达式收集
[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
Why do novices often fail to answer questions in the programming community, and even get ridiculed?