Lesson 21 using a cursor
This lesson will be taught what is 游标
and how to use 游标
.
21.1 Cursor
SQL
Returns a set of retrieval operation called结果集
rows, which rows are returned to the group ofSQL
statement rows match (zero or more rows).
Sometimes, the need to move forward or backward in one or more rows retrieved row, which is where the use of the cursor.
游标cursor
Is stored in aDBMS
database query on the server, it is not aSELECT
statement, but the statement is retrieved result set.
After storing the cursor, the application may need to scroll or browse the data.
Cursor options and features:
- It can be marked as read-only cursor, so that the data can be read, but not update, and delete.
- To control the orientation operation can be performed (forward, backward, first, last, absolute position, relative position, etc.).
- Some markers can be editable as, as some non-editable.
- A predetermined range, it causes the cursor to create a specific request (such as stored procedures) or accessible to all requests.
- Indicates the
DBMS
data retrieved, (rather than point out a table activity data) to copy the data open and during the visit does not change the cursor.
Cursor is mainly used for interactive applications, where the user needs to scroll through the data on the screen, and the data can be browsed or make changes.
21.2 Use the cursor
Use the cursor involves several clear steps:
- Before using the cursor, you must declare (define) it. This process is not actually retrieve the data, it is only definition to use
SELECT
statements and cursor options. - Once declared, it must open a cursor for use. This process using the previously defined
SELECT
statement to actual data retrieved. - For cursors filled with data, taken as needed (retrieve) the rows.
- At the end of the cursor, you must close the cursor, if possible, release the cursor (depends on concrete
DBMS
).
After declaring a cursor, the cursor can be opened and closed frequently as needed. When the cursor is open, fetch operation may be performed as frequently as necessary.
21.2.1 create a cursor
- Use the
DECLARE
statement to create a cursor. DECLARE
Named cursor, and define the appropriateSELECT
sentence, as required withWHERE
other clauses.
21.2.2 Use the cursor
- Use the
OPEN CURSOR
statement to open a cursor. - You can now
FETCH
access the data cursor statement.FETCH
Indicate which rows to retrieve, from where to retrieve them and put them in where (such as variable names).
21.2.3 Close the cursor
SQL Server
And so DBMS
it requires a clear release the resources occupied by the cursor.
CLOSE
Statement is used to close the cursor. Once the cursor is closed, if you do not open again, it will not be used. The second time using it do not need to declare, justOPEN
open it can be.