Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Cursor (databases)

From Wikipedia, the free encyclopedia
Database systems concept
This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages)
This articlecontainsinstructions or advice. Wikipedia is not a guidebook; please helprewrite such content to be encyclopedic or move it toWikiversity,Wikibooks, orWikivoyage.(September 2019)
This article includes alist of references,related reading, orexternal links,but its sources remain unclear because it lacksinline citations. Please helpimprove this article byintroducing more precise citations.(September 2019) (Learn how and when to remove this message)
(Learn how and when to remove this message)

Incomputer science, adatabasecursor is a mechanism that enablestraversal over therecords in a database. Cursors facilitate processing in conjunction with the traversal, such as retrieval, addition and removal of database records. The database cursor characteristic of traversal makes cursors akin to the programming language concept ofiterator.

Cursors are used by database programmers to process individual rows returned bydatabase system queries. Cursors enable manipulation of wholeresult sets at once. In this scenario, a cursor enables the sequential processing of rows in a result set.

In SQL procedures, a cursor makes it possible to define a result set (a set of data rows) and perform complex logic on a row by row basis. By using the same mechanics, a SQL procedure can also define a result set and return it directly to the caller of the SQL procedure or to a client application.

A cursor can be viewed as a pointer to one row in a set of rows. The cursor can only reference one row at a time, but can move to other rows of the result set as needed.

Usage

[edit]

To use cursors in SQL procedures, you need to do the following:

  1. Declare a cursor that defines a result set
  2. Open the cursor to establish the result set
  3. Fetch the data into local variables as needed from the cursor, one row at a time
  4. Close the cursor when done

To work with cursors you must use the following SQL statements

This section introduces the ways theSQL:2003 standard defines how to use cursors in applications in embedded SQL. Not all application bindings for relational database systems adhere to that standard, and some (such asCLI orJDBC) use a different interface.

A programmer makes a cursor known to theDBMS by using aDECLARE ...CURSOR statement and assigning the cursor a (compulsory) name:

 DECLAREcursor_name CURSOR IS SELECT ... FROM ...

Before code can access the data, it must open the cursor with theOPEN statement. Directly following a successful opening, the cursor is positionedbefore the first row in the result set.

 OPENcursor_name

Applications position cursors on a specific row in the result set with theFETCH statement. A fetch operation transfers the data of the row into the application.

 FETCHcursor_name INTO ...

Once an application has processed all available rows or the fetch operation is to be positioned on a non-existing row (comparescrollable cursors below), the DBMS returns a SQLSTATE '02000' (usually accompanied by anSQLCODE +100) to indicate the end of the result set.

The final step involves closing the cursor using theCLOSE statement:

 CLOSEcursor_name

After closing a cursor, a program can open it again, which implies that the DBMS re-evaluates the same query or a different query and builds a new result set.

Scrollable cursors

[edit]

Programmers may declare cursors as scrollable or not scrollable. The scrollability indicates the direction in which a cursor can move.

With anon-scrollable (orforward-only) cursor, you canFETCH each row at most once, and the cursor automatically moves to the next row. After you fetch the last row, if you fetch again, you will put the cursor after the last row and get the following code:SQLSTATE 02000 (SQLCODE +100) .

A program may position ascrollable cursor anywhere in the result set using theFETCH SQL statement. The keyword SCROLL must be specified when declaring the cursor. The default isNO SCROLL, although different language bindings like JDBC may apply a different default.

 DECLAREcursor_namesensitivitySCROLL CURSOR FOR SELECT ... FROM ...

The target position for a scrollable cursor can be specified relatively (from the current cursor position) or absolutely (from the beginning of the result set).

 FETCH [ NEXT | PRIOR | FIRST | LAST ] FROMcursor_name
 FETCH ABSOLUTEn FROMcursor_name
 FETCH RELATIVEn FROMcursor_name;

Scrollable cursors can potentially access the same row in the result set multiple times. Thus, data modifications (insert, update, delete operations) from other transactions could affect the result set. A cursor can be SENSITIVE or INSENSITIVE to such data modifications. A sensitive cursor picks up data modifications affecting the result set of the cursor, and an insensitive cursor does not. Additionally, a cursor may be INSENSITIVE, in which case the DBMS tries to apply sensitivity as much as possible.

"WITH HOLD"

[edit]

Cursors are usually closed automatically at the end of a transaction, i.e. when a COMMIT or ROLLBACK (or an implicit termination of the transaction) occurs. That behavior can be changed if the cursor is declared using the WITH HOLD clause (the default is WITHOUT HOLD). A holdable cursor is kept open over COMMIT and closed upon ROLLBACK. (Some DBMS deviate from this standard behavior and also keep holdable cursors open over ROLLBACK.)

 DECLAREcursor_name CURSORWITH HOLD  FOR SELECT .... FROM ....

When a COMMIT occurs, a holdable cursor is positionedbefore the next row. Thus, a positionedUPDATE or positionedDELETE statement will only succeed after a FETCH operation occurred first in the transaction.

Note that JDBC defines cursors as holdable per default. This is done because JDBC also activates auto-commit per default.

Positioned update/delete statements

[edit]

Cursors can not only be used to fetch data from the DBMS into an application but also to identify a row in a table to be updated or deleted. The SQL:2003 standard defines positioned update and positioned delete SQL statements for that purpose. Such statements do not use a regular WHERE clause with predicates. Instead, a cursor identifies the row. The cursor must be opened and already positioned on a row by means ofFETCH statement.

 UPDATEtable_name SET    ... WHERECURRENT OFcursor_name
 DELETE FROMtable_name WHERECURRENT OFcursor_name

The cursor must operate on an updatable result set in order to successfully execute a positioned update or delete statement. Otherwise, the DBMS would not know how to apply the data changes to the underlying tables referred to in the cursor.

Cursors in distributed transactions

[edit]

Using cursors in distributed transactions (X/Open XA Environments), which are controlled using a transaction monitor, is no different from cursors in non-distributed transactions.

One has to pay attention when usingholdable cursors, however. Connections can be used by different applications. Thus, once a transaction has been ended and committed, a subsequent transaction (running in a different application) could inherit existing holdable cursors. Herefore, an application developer has to be aware of that situation.

Cursors in XQuery

[edit]

TheXQuery language allows cursors to be created using thesubsequence() function.

The format is:

let$displayed-sequence:=subsequence($result,$start,$item-count)

Where $result is the result of the initial XQuery,$start is the item number to start and$item-count is the number of items to return.

Equivalently this can also be done using a predicate:

let$displayed-sequence:=$result[$startto$end]

Where$end is the end sequence.

For complete examples see theXQuery/Searching,Paging and Sorting#Paging at Wikibooks.

Disadvantages of cursors

[edit]

The following information may vary depending on the specific database system.

Fetching a row from the cursor may result in anetwork round trip each time. This uses much more network bandwidth than would ordinarily be needed for the execution of a single SQL statement like DELETE. Repeated network round trips can severely reduce the speed of the operation using the cursor. Some DBMSs try to reduce this effect by using block fetch. Block fetch implies that multiple rows are sent together from the server to the client. The client stores a whole block of rows in a local buffer and retrieves the rows from there until that buffer is exhausted.

Cursors allocateresources on the server, such aslocks, packages, processes, and temporary storage. For example,Microsoft SQL Server implements cursors by creating a temporary table and populating it with the query's result set. If a cursor is not properly closed (deallocated), the resources will not be freed until the SQL session (connection) itself is closed. This wasting of resources on the server can lead to performance degradations and failures.

Example

[edit]

EMPLOYEES TABLE

SQL>descEMPLOYEES_DETAILS; Name            Null?     Type --------------- --------  ------------ EMPLOYEE_ID     NOT NULL  NUMBER(6) FIRST_NAME                VARCHAR2(20) LAST_NAME       NOT NULL  VARCHAR2(25) EMAIL           NOT NULL  VARCHAR2(30) PHONE_NUMBER              VARCHAR2(20) HIRE_DATE       NOT NULL  DATE JOB_ID          NOT NULL  VARCHAR2(10) SALARY                    NUMBER(8,2) COMMISSION_PCT            NUMBER(2,2) MANAGER_ID                NUMBER(6) DEPARTMENT_ID             NUMBER(4)
SAMPLECURSORKNOWNASEECREATEORREPLACEPROCEDUREEEASBEGINDECLAREv_employeeIDEMPLOYEES_DETAILS.EMPLOYEE_ID%TYPE;v_FirstNameEMPLOYEES_DETAILS.FIRST_NAME%TYPE;v_LASTNameEMPLOYEES_DETAILS.LAST_NAME%TYPE;v_JOB_IDEMPLOYEES_DETAILS.JOB_ID%TYPE:='IT_PROG';Cursorc_EMPLOYEES_DETAILSISSELECTEMPLOYEE_ID,FIRST_NAME,LAST_NAMEFROMEMPLOYEES_DETAILSWHEREJOB_ID='v_JOB_ID';BEGINOPENc_EMPLOYEES_DETAILS;LOOPFETCHc_EMPLOYEES_DETAILSINTOv_employeeID,v_FirstName,v_LASTName;DBMS_OUTPUT.put_line(v_employeeID);DBMS_OUTPUT.put_line(v_FirstName);DBMS_OUTPUT.put_line(v_LASTName);EXITWHENc_EMPLOYEES_DETAILS%NOTFOUND;ENDLOOP;CLOSEc_EMPLOYEES_DETAILS;END;END;

See also

[edit]

References

[edit]

External links

[edit]
Types
Concepts
Objects
Components
Functions
Related topics
Retrieved from "https://en.wikipedia.org/w/index.php?title=Cursor_(databases)&oldid=1271809520"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp