当前位置:网站首页>100 important knowledge points that SQL must master: using cursors
100 important knowledge points that SQL must master: using cursors
2022-07-02 21:50:00 【Gu Ge academic】
This lesson will teach you what a cursor is , How to use cursors .
21.1 The cursor
SQL The retrieval operation returns a set of rows called the result set , This group of returned lines are all related to SQL sentence
Matching lines ( Zero line to multiple lines ). Simply use SELECT sentence , There is no way to get the number
a line 、 Next line or before 10 That's ok . But this is the relationship DBMS Functional components .
Result set (result set)
SQL The results retrieved by the query .
Sometimes , Need to move forward or backward one or more lines in the retrieved lines , This is the use of cursors
Where to go . The cursor (cursor) Is a store in DBMS Database query on server ,
It's not one SELECT sentence , But the result set retrieved by the statement . In storage
After cursor , The application can scroll or browse the data as needed .
explain :SQLite Support
SQLite Supported cursors are called steps (step), The basic concepts described in this lesson apply to
SQLite Steps for , But the grammar may be completely different .
Different DBMS Support different cursor options and features . Some common options and features are as follows .
Can mark cursor as read-only , Enable data to be read , But you can't update and delete .
Can control the directional operation that can be performed ( forward 、 backward 、 First of all 、 Last 、 Absolute position and
Relative position, etc ).
Can mark some columns as editable , Some columns are not editable .
Prescribed scope , Make the cursor respond to the specific request to create it ( Like stored procedures ) Or for all requests
Accessible .
instructions DBMS For the retrieved data ( Instead of pointing out the activity data in the table ) replicate ,
Keep data unchanged during cursor opening and access .
Cursors are mainly used for interactive applications , The user needs to scroll the data on the screen , And the data
Browse or make changes .
21.2 Use cursors
Using cursors involves several explicit steps .
Before using the cursor , You must declare ( Definition ) it . This process does not actually retrieve data ,
It just defines what to use SELECT Statement and cursor options .
Once declared , You must open the cursor for use . This process uses the SELECT
Statement to actually retrieve the data .
For data filled cursors , Remove as needed ( retrieval ) All walks of life .
When ending cursor usage , Cursor must be closed , If possible , Release cursor ( Rely on tools
Somatic DBMS).
After declaring the cursor , The cursor can be opened and closed frequently as needed . When the cursor is open , Rootable
Perform fetch operations as often as needed .
21.2.1 Create cursors
Use DECLARE Statement create cursor , This statement is in different DBMS It's different .
DECLARE Named cursor , And define the corresponding SELECT sentence , Bring... As needed WHERE and
Other clauses . To illustrate , We create a cursor to retrieve all places without email addresses
There are customers , As part of the application , Help operators find out the vacant email
Address .
The following is how to create this cursor DB2、MariaDB、MySQL and SQL Server edition .
Input ▼
DECLARE CustCursor CURSOR
FOR
SELECT * FROM Customers
WHERE cust_email IS NULL;
Here is Oracle and PostgreSQL edition :
Input ▼
DECLARE CURSOR CustCursor
IS
SELECT * FROM Customers
WHERE cust_email IS NULL;
analysis ▼
In the above two versions , DECLARE Statement is used to define and name cursors , Here for
CustCursor . SELECT Statement defines a containing no email address ( NULL value )
Cursor of all customers .
After defining the cursor , You can open it .
21.2.2 Use cursors
Use OPEN CURSOR Statement open cursor , This statement is simple , In most DBMS
The syntax in is the same :
Input ▼
OPEN CURSOR CustCursor
analysis ▼
Processing OPEN CURSOR When the sentence is , Execute the query , Store the retrieved data for browsing and
rolling .
Now we can use FETCH Statement accesses cursor data . FETCH Indicate which rows to retrieve , from
Where to retrieve them and where to put them ( Such as variable name ). The first example uses Oracle
Syntax retrieves a row from the cursor ( first line ):
Input ▼
DECLARE TYPE CustCursor IS REF CURSOR
RETURN Customers%ROWTYPE;
DECLARE CustRecord Customers%ROWTYPE
BEGIN
OPEN CustCursor;
FETCH CustCursor INTO CustRecord;
CLOSE CustCursor;
END;
analysis ▼
In this case , FETCH Used to retrieve the current line ( Automatically start with the first line ), Put it in the statement
The variable of CustRecord in . The retrieved data will not be processed .
The next example ( Also used Oracle grammar ) in , From the first line to the last line , Cycle the retrieved data :
Input ▼
DECLARE TYPE CustCursor IS REF CURSOR
RETURN Customers%ROWTYPE;
DECLARE CustRecord Customers%ROWTYPE
BEGIN
OPEN CustCursor;
LOOP
FETCH CustCursor INTO CustRecord;
EXIT WHEN CustCursor%NOTFOUND;
...
END LOOP;
CLOSE CustCursor;
END;
analysis ▼
As in the previous example , This example uses FETCH Retrieve the current row , Put it in a place called
CustRecord Variables in . But the difference is , there FETCH be located LOOP Inside , because
This is repeated . Code EXIT WHEN CustCursor%NOTFOUND Make it impossible to take out more
Terminate processing when there are more rows ( Exit loop ). This example does not do the actual processing , Practical example
The ellipsis can be replaced by the specific processing code in the sub .
Here's another example , This use Microsoft SQL Server grammar :
Input ▼
DECLARE @cust_id CHAR(10),
@cust_name CHAR(50),
@cust_address CHAR(50),
@cust_city CHAR(50),
@cust_state CHAR(5),
@cust_zip CHAR(10),
@cust_country CHAR(50),
@cust_contact CHAR(50),
@cust_email CHAR(255)
21.2 Use cursors | | 201
OPEN CustCursor
FETCH NEXT FROM CustCursor
INTO @cust_id, @cust_name, @cust_address,
@cust_city, @cust_state, @cust_zip,
@cust_country, @cust_contact, @cust_email
...
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM CustCursor
INTO @cust_id, @cust_name, @cust_address,
@cust_city, @cust_state, @cust_zip,
@cust_country, @cust_contact, @cust_email
...
END
CLOSE CustCursor analysis ▼
In this case , Declare a variable for each retrieved column , FETCH Statement to retrieve a row and save
Value into these variables . Use WHILE Cycle through each row , Conditions WHILE @@FETCH_
STATUS = 0 Terminate processing when no more rows can be fetched ( Exit loop ). This example is not
Carry out specific treatment , In the actual code , You should replace them with specific processing code ... .
21.2.3 Close cursor
As mentioned in the previous examples , The cursor needs to be closed when it is used . Besides ,SQL Server
etc. DBMS It is required to explicitly release the resources occupied by the cursor . Here is DB2、Oracle and
PostgreSQL The grammar of .
Input ▼
CLOSE CustCursor
Here is Microsoft SQL Server Version of .
Input ▼
CLOSE CustCursor
DEALLOCATE CURSOR CustCursor
analysis ▼
CLOSE Statement to close the cursor . Once the cursor is closed , If you don't open it again , Will not make
use . The second time you use it, you don't need to declare , Just use OPEN Open it and .
边栏推荐
- D4:非成对图像去雾,基于密度与深度分解的自增强方法(CVPR 2022)
- Error in PIP installation WHL file: error: is not a supported wheel on this platform
- Construction and maintenance of business websites [8]
- Construction and maintenance of business website [5]
- Daily book CSO advanced road first exposed
- Research Report on micro gripper industry - market status analysis and development prospect prediction
- 发现你看不到的物体!南开&武大&ETH提出用于伪装目标检测SINet,代码已开源!...
- 记录一下微信、QQ、微博分享web网页功能
- [Jianzhi offer] 56 - ii Number of occurrences of numbers in the array II
- Three chess games
猜你喜欢

Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source

Blue Bridge Cup Winter vacation homework (DFS backtracking + pruning)

LandingSite eBand B1冒烟测试用例
![[shutter] shutter layout component (Introduction to layout component | row component | column component | sizedbox component | clipoval component)](/img/45/735431f59a84e9554225a72a551ab8.jpg)
[shutter] shutter layout component (Introduction to layout component | row component | column component | sizedbox component | clipoval component)

Oriental Aesthetics and software design

TinyMCE visual editor adds Baidu map plug-in

How to test the process of restoring backup files?

System (hierarchical) clustering method and SPSS implementation

D4:非成对图像去雾,基于密度与深度分解的自增强方法(CVPR 2022)

MySQL learning record (3)
随机推荐
[shutter] shutter layout component (opacity component | clipprect component | padding component)
暑期第一周总结
MySQL learning record (2)
图像基础概念与YUV/RGB深入理解
How to write a good program when a big book speaks every day?
VIM command-t plugin error: unable to load the C extension - VIM command-t plugin error: could not load the C extension
Accounting regulations and professional ethics [16]
Destroy in beforedestroy invalid value in localstorage
[shutter] shutter gesture interaction (click event handling | click OnTap | double click | long press | click Cancel | press ontapdown | lift ontapup)
Introduction to the principle of geographical detector
How do I access the kubernetes API?
The difference between include < > and include ""
MySQL learning record (6)
China's crude oil heater market trend report, technological innovation and market forecast
Baidu sued a company called "Ciba screen"
Cloud computing technology [1]
Find objects you can't see! Nankai & Wuhan University & eth proposed sinet for camouflage target detection, and the code has been open source
tinymce可视化编辑器增加百度地图插件
A specially designed loss is used to deal with data sets with unbalanced categories
技术人创业:失败不是成功,但反思是