当前位置:网站首页>[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
WHERE
andHAVING
, Or a keyword that limits the return recordLIMIT
Return 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()
”, StatementIN
Parameterslimit_total_salary
,DOUBLE type ; StatementOUT
Parameterstotal_count
,INT
type . The function can accumulate the salary values of several employees with the highest salary , Until the total salary reacheslimit_total_salary
The 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 one
The 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 .
边栏推荐
- [weekly pit] information encryption + [answer] positive integer factorization prime factor
- OLED屏幕的使用
- Comment faire une radio personnalisée
- 2022 nurse (primary) examination questions and new nurse (primary) examination questions
- Recyclerview GridLayout bisects the middle blank area
- PG basics -- Logical Structure Management (transaction)
- use. Net drives the OLED display of Jetson nano
- 【每周一坑】正整数分解质因数 +【解答】计算100以内质数之和
- The mail command is used in combination with the pipeline command statement
- [DIY]如何制作一款個性的收音機
猜你喜欢
SAP Fiori应用索引大全工具和 SAP Fiori Tools 的使用介绍
Design your security architecture OKR
2022 nurse (primary) examination questions and new nurse (primary) examination questions
【mysql】触发器
强化学习-学习笔记5 | AlphaGo
知识图谱构建流程步骤详解
1_ Introduction to go language
防火墙基础之外网服务器区部署和双机热备
Value of APS application in food industry
使用.Net驱动Jetson Nano的OLED显示屏
随机推荐
What programming do children learn?
What is the difference between procedural SQL and C language in defining variables
[weekly pit] output triangle
全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
The mail command is used in combination with the pipeline command statement
Use of OLED screen
Pytest (3) - Test naming rules
Logic is a good thing
数据湖(八):Iceberg数据存储格式
[diy] how to make a personalized radio
OLED屏幕的使用
新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
'class file has wrong version 52.0, should be 50.0' - class file has wrong version 52.0, should be 50.0
性能测试过程和计划
看过很多教程,却依然写不好一个程序,怎么破?
Implementation of packaging video into MP4 format and storing it in TF Card
How to turn a multi digit number into a digital list
15 millions d'employés sont faciles à gérer et la base de données native du cloud gaussdb rend le Bureau des RH plus efficace
Detailed explanation of knowledge map construction process steps
Mécanisme de fonctionnement et de mise à jour de [Widget Wechat]