ch4 cursors
TRANSCRIPT
-
8/6/2019 Ch4 Cursors
1/34
Cursors
-
8/6/2019 Ch4 Cursors
2/34
SQL Cursor
A cursor is a private SQL work area. There are two types of cursors:
o Implicit cursorso Explicit cursors
The Oracle Server uses implicit cursors toparse and execute your SQL statements.
Explicit cursors are explicitly declared bythe programmer.
-
8/6/2019 Ch4 Cursors
3/34
Cursors
Pointer to memory location on databaseservero DBMS uses to process a SQL query
Use to:o Retrieve and manipulate database data in
PL/SQL programs
Types:o Implicito Explicit
-
8/6/2019 Ch4 Cursors
4/34
Cursor
Context Area
activeset
Numberofrows
processed
Parsedcommandstatement
Database ServerMemory
-
8/6/2019 Ch4 Cursors
5/34
ImplicitCursors
Context areao Contains information about queryo Created by INSERT, UPDATE, DELETE, or
SELECT Active set
o Set of data rows that query retrieves
Implicit cursoro Pointer to context area
-
8/6/2019 Ch4 Cursors
6/34
ImplicitCursors (continued)
Use to assign output of SELECT query toPL/SQL program variablesoWhen query will return only one record
-
8/6/2019 Ch4 Cursors
7/34
ImplicitCursors (continued)
Useful to use %TYPE reference data typeo To declare variables used with implicit cursors
Error ORA-01422: exact fetch returns
more than requested number of rowso Implicit cursor query tried to retrieve multiple
records
-
8/6/2019 Ch4 Cursors
8/34
SQL CursorAttributes
Using SQL cursor attributes, you cantest the outcome of your SQLstatements.SQL%ROWCOUNTNumberofrowsaffectedbythemost
recent SQL statement (anintegervalue)
SQL%FOUND BooleanattributethatevaluatestoTRUE ifthemostrecent SQL statementaffectsoneormorerowsSQL%NOTFOUND BooleanattributethatevaluatestoTRUEifthemostrecent SQL statementdoesnotaffectanyrowsSQL%ISOPEN Alwaysevaluatesto FALSE becausePL/SQLclosesimplicitcursorsimmediatelyaftertheyareexecuted
-
8/6/2019 Ch4 Cursors
9/34
SQL CursorAttributes
Delete rows that have the specifiedorder number from the ITEM table.Print the number of rows deleted.
ExampleVARIABLE rows_deletedVARCHAR2(30)DECLAREv_ordidNUMBER := 605;BEGINDELETE FROM itemWHERE ordid = v_ordid;
:rows_deleted := (SQL%ROWCOUNT ||' rowsdeleted.');END;/PRINTrows_deleted
-
8/6/2019 Ch4 Cursors
10/34
ImplicitCursorSQL%ROWCOUNT Example
SQL> SET SERVEROUTPUT ON;SQL> DECLARErNUMBER;
BEGINDELETE FROM empWHERE empno=7900;r:=SQL%ROWCOUNT;DBMS_OUTPUT.PUT_LINE(r);
END;/1
-
8/6/2019 Ch4 Cursors
11/34
ImplicitCursorSQL%FOUNDExample
SQL> DECLARErBOOLEAN;BEGINDELETE FROM empWHERE empno=1000;r:=SQL%FOUND;IF r THENDBMS_OUTPUT.PUT_LINE('Rows are founded');ELSEDBMS_OUTPUT.PUT_LINE('No Rows are founded');ENDIF;
END;
/No Rows are founded
-
8/6/2019 Ch4 Cursors
12/34
ImplicitCursorSQL%ISOPENExample
SQL> DECLARErBOOLEAN;BEGINUPDATE emp SET sal=1000WHERE empno>7900;r:=SQL%ISOPEN;IF r THENDBMS_OUTPUT.PUT_LINE('The cursor is opened');ELSEDBMS_OUTPUT.PUT_LINE('The cursor is closed');ENDIF;
END;
/The cursor is closed
-
8/6/2019 Ch4 Cursors
13/34
AboutCursors
Every SQL statement executedby the Oracle Server has an
individual cursor associated withit:o Implicit cursors: Declared for allDML and PL/SQL SELECT
statementso Explicit cursors: Declared and
named by the programmer
-
8/6/2019 Ch4 Cursors
14/34
ExplicitCursorFunctions
Activeset
CurrentrowCursor
7369 SMITHCLERK
7566 JONES MANAGER7788 SCOTT ANALYST7876 ADAMS CLERK7902 FORD ANALYST
-
8/6/2019 Ch4 Cursors
15/34
Controlling ExplicitCursors
CreateanamedSQL
area
DECLARE
Identifytheactiveset
OPEN
Loadthecurrentrowinto
variables
FETCH
Testforexistingrows
EMPTY?
ReturntoFETCHifrowsfound
No
Releasetheactiveset
CLOSE
Yes
-
8/6/2019 Ch4 Cursors
16/34
Controlling ExplicitCursors
Openthecursor.
Cursor
Pointer
Fetcharowfromthecursor.
Cursor
Pointer
Continueuntil empty.
Cursor
Pointer
Closethecursor.
-
8/6/2019 Ch4 Cursors
17/34
DeclaringtheCursor
Syntax
Do not include the INTO clause in thecursor declaration.
If processing rows in a specific sequence isrequired, use the ORDER BY clause in the
query.
CURSOR cursor_name ISselect_statement;
-
8/6/2019 Ch4 Cursors
18/34
DeclaringtheCursor
ExampleDECLARECURSOR emp_cursorISSELECTempno,enameFROM emp;
CURSOR dept_cursorISSELECT *FROM deptWHERE deptno = 10;BEGIN
...
-
8/6/2019 Ch4 Cursors
19/34
OpeningtheCursor
Syntax
Open the cursor to execute the query and
identify the active set. If the query returns no rows, no exception israised.
Use cursor attributes to test the outcomeafter a fetch.
OPENcursor_name;
-
8/6/2019 Ch4 Cursors
20/34
FetchingDatafromtheCursor
Syntax
Retrieve the current row values into variables.
Include the same number of variables. Match each variable to correspond to the columns
positionally. Test to see if the cursor contains rows.
The FETCH statement performs thefollowing operations:
1. Advances the pointer to the next row in the activeset.2. Reads the data for the current row into the outputPL/SQL variables.
FETCH cursor_name INTO [variable1, variable2, ...]| record_name];
-
8/6/2019 Ch4 Cursors
21/34
FetchingDatafromtheCursor
Examples
FETCHemp_cursorINTO v_empno,v_ename;
...OPENdefined_cursor;LOOPFETCHdefined_cursorINTO defined_variablesEXIT WHEN...;
...-- Processtheretrieveddata
...END;
-
8/6/2019 Ch4 Cursors
22/34
ClosingtheCursor
Syntax
Close the cursor after completing theprocessing of the rows. Reopen the cursor, if required. Do not attempt to fetch data from a cursor
once it has been closed. The CLOSE statement releases the context
area.
CLOSE cursor_name;
-
8/6/2019 Ch4 Cursors
23/34
ExplicitCursorExample
SQL> DECLAREv_num emp.empno%TYPE;v_name emp.ename%TYPE;CURSOR my_cursorIS SELECT empno,ename FROM empWHEREempno>7900;
BEGINOPENmy_cursor;LOOPFETCHmy_cursorINTO v_num,v_name;EXITWHENmy_cursor%NOTFOUND;DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name);END LOOP;CLOSE my_cursor;END;/7902 has the name FORD7934 has the name MILLER
-
8/6/2019 Ch4 Cursors
24/34
ExplicitCursorAttributes
Obtain status information about acursor.AttributeTypeDescription
%ISOPEN Boolean EvaluatestoTRUE ifthecursorisopen%NOTFOUND Boolean EvaluatestoTRUE ifthemostrecentfetchdoesnotreturnarow
%FOUND Boolean EvaluatestoTRUE ifthemostrecentfetchreturnsarow; complementof%NOTFOUND%ROWCOUNTNumberEvaluatestothetotal numberofrowsreturnedsofar
-
8/6/2019 Ch4 Cursors
25/34
Controlling Multiple Fetches
Process several rows from an explicitcursor using a loop.
Fetch a row with each iteration.
Use the %NOTFOUND attribute to write atest for an unsuccessful fetch.
Use explicit cursor attributes to test thesuccess of each fetch.
-
8/6/2019 Ch4 Cursors
26/34
-
8/6/2019 Ch4 Cursors
27/34
The %NOTFOUND
and %ROWCOUNT Attributes
Use the %ROWCOUNT cursor attribute toretrieve an exact number of rows.
The value of %ROWCOUNT beforefetching any row is NULL.
Use the %NOTFOUND cursor attribute todetermine when to exit the loop.
-
8/6/2019 Ch4 Cursors
28/34
ExplicitCursor%ISOPENExample
SQL> DECLAREv_num emp.empno%TYPE;v_name emp.ename%TYPE;rBOOLEAN;CURSOR my_cursorIS SELECT empno,ename FROM empWHERE
empno>7900;BEGINOPENmy_cursor;r:=my_cursor%ISOPEN;IF r THENDBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open statement');ELSEDBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open statement');ENDIF;
-
8/6/2019 Ch4 Cursors
29/34
ExplicitCursor%ISOPENExampleCont.
LOOPFETCHmy_cursorINTO v_num,v_name;EXITWHENmy_cursor%NOTFOUND;END LOOP;CLOSE my_cursor;
r:=my_cursor%ISOPEN;IF r THENDBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close statement');ELSEDBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close statement');ENDIF;END;/The Cursor is opened after the open statementThe Cursor is closed after the close statement
-
8/6/2019 Ch4 Cursors
30/34
-
8/6/2019 Ch4 Cursors
31/34
Cursorsand Records
Process the rows of the active setconveniently by fetching values into aPL/SQL RECORD.
Exam
pleDECLARECURSOR emp_cursorISSELECTempno,enameFROM emp;emp_recordemp_cursor%ROWTYPE;
BEGI
NOPENemp_cursor;LOOPFETCHemp_cursorINTO emp_record;...
-
8/6/2019 Ch4 Cursors
32/34
Syntax
The cursor FOR loop is a shortcut toprocess explicit cursors.
Implicit open, fetch, and close occur. The record is implicitly declared.
CursorFOR Loops
FOR record_name INcursor_name LOOPstatement1;statement2;...
END LOOP;
-
8/6/2019 Ch4 Cursors
33/34
CursorFOR Loops
Retrieve employees one by one untilno more are left.
Example
DECLARECURSOR emp_cursorISSELECTename,deptnoFROM emp;BEGINFOR emp_recordINemp_cursorLOOP
-- implicitopenandimplicitfetchoccurIF emp_record.deptno = 30 THEN...END LOOP; -- implicitcloseoccursEND;
-
8/6/2019 Ch4 Cursors
34/34
Summary
Cursor types:o Implicit cursors: Used for all DML statements
and single-row queries.o Explicit cursors: Used for queries of zero, one, orm
ore rows. You can manipulate explicit cursors. You can evaluate the cursor status by using
cursor attributes. You can use cursor FOR loops.