Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two.

Similar presentations


Presentation on theme: "1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two."— Presentation transcript:

1 1 CursorsCursors

2 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two types of cursors: Implicit cursors Implicit cursors Explicit cursors Explicit cursors The Oracle Server uses implicit cursors to parse and execute your SQL statements. The Oracle Server uses implicit cursors to parse and execute your SQL statements. Explicit cursors are explicitly declared by the programmer. Explicit cursors are explicitly declared by the programmer. A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two types of cursors: Implicit cursors Implicit cursors Explicit cursors Explicit cursors The Oracle Server uses implicit cursors to parse and execute your SQL statements. The Oracle Server uses implicit cursors to parse and execute your SQL statements. Explicit cursors are explicitly declared by the programmer. Explicit cursors are explicitly declared by the programmer.

3 3 Cursors Pointer to memory location on database server Pointer to memory location on database server DBMS uses to process a SQL query DBMS uses to process a SQL query Use to: Use to: Retrieve and manipulate database data in PL/SQL programs Retrieve and manipulate database data in PL/SQL programs Types: Types: Implicit Implicit Explicit Explicit

4 4 Cursor Context Area active set Number of rows processed Parsed command statement Database Server Memory

5 5 Implicit Cursors Context area Context area Contains information about query Contains information about query Created by INSERT, UPDATE, DELETE, or SELECT Created by INSERT, UPDATE, DELETE, or SELECT Active set Active set Set of data rows that query retrieves Set of data rows that query retrieves Implicit cursor Implicit cursor Pointer to context area Pointer to context area

6 6 Implicit Cursors (continued) Use to assign output of SELECT query to PL/SQL program variables Use to assign output of SELECT query to PL/SQL program variables When query will return only one record When query will return only one record

7 7 Implicit Cursors (continued) Useful to use %TYPE reference data type Useful to use %TYPE reference data type To declare variables used with implicit cursors To declare variables used with implicit cursors Error “ORA-01422: exact fetch returns more than requested number of rows” Error “ORA-01422: exact fetch returns more than requested number of rows” Implicit cursor query tried to retrieve multiple records Implicit cursor query tried to retrieve multiple records

8 8 SQL Cursor Attributes Using SQL cursor attributes, you can test the outcome of your SQL statements. Using SQL cursor attributes, you can test the outcome of your SQL statements. SQL%ROWCOUNTNumber of rows affected by the most recent SQL statement (an integervalue) SQL%FOUNDBoolean attribute that evaluates to TRUE if the most recent SQL statement affects oneor more rows SQL%NOTFOUNDBoolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows SQL%ISOPENAlways evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed

9 9 SQL Cursor Attributes Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Example Example Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Delete rows that have the specified order number from the ITEM table. Print the number of rows deleted. Example Example VARIABLE rows_deleted VARCHAR2(30) DECLARE v_ordid NUMBER := 605; BEGIN DELETE FROM item WHERE ordid = v_ordid; :rows_deleted := (SQL%ROWCOUNT || ' rows deleted.'); END; / PRINT rows_deleted

10 10 Implicit Cursor SQL%ROWCOUNT Example SQL> SET SERVEROUTPUT ON; SQL> DECLARE r NUMBER; r NUMBER; BEGIN BEGIN DELETE FROM emp WHERE empno=7900; DELETE FROM emp WHERE empno=7900; r:=SQL%ROWCOUNT; r:=SQL%ROWCOUNT; DBMS_OUTPUT.PUT_LINE(r); DBMS_OUTPUT.PUT_LINE(r); END; END; /1

11 11 Implicit Cursor SQL%FOUND Example SQL> DECLARE r BOOLEAN; r BOOLEAN; BEGIN BEGIN DELETE FROM emp WHERE empno=1000; DELETE FROM emp WHERE empno=1000; r:=SQL%FOUND; r:=SQL%FOUND; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('Rows are founded'); DBMS_OUTPUT.PUT_LINE('Rows are founded'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('No Rows are founded'); DBMS_OUTPUT.PUT_LINE('No Rows are founded'); END IF; END IF; END; END; / No Rows are founded

12 12 Implicit Cursor SQL%ISOPEN Example SQL> DECLARE r BOOLEAN; r BOOLEAN; BEGIN BEGIN UPDATE emp SET sal=1000 WHERE empno>7900; UPDATE emp SET sal=1000 WHERE empno>7900; r:=SQL%ISOPEN; r:=SQL%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The cursor is opened'); DBMS_OUTPUT.PUT_LINE('The cursor is opened'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('The cursor is closed'); DBMS_OUTPUT.PUT_LINE('The cursor is closed'); END IF; END IF; END; END; / The cursor is closed

13 13 About Cursors Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Implicit cursors: Declared for all DML and PL/SQL SELECT statements Implicit cursors: Declared for all DML and PL/SQL SELECT statements Explicit cursors: Declared and named by the programmer Explicit cursors: Declared and named by the programmer Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Implicit cursors: Declared for all DML and PL/SQL SELECT statements Implicit cursors: Declared for all DML and PL/SQL SELECT statements Explicit cursors: Declared and named by the programmer Explicit cursors: Declared and named by the programmer

14 14 Explicit Cursor Functions Active set Current row Cursor 7369SMITHCLERK 7566JONESMANAGER 7788SCOTTANALYST 7876ADAMSCLERK 7902FORDANALYST

15 15 Controlling Explicit Cursors Create a named SQL area Create a named SQL area DECLAREDECLARE Identify the active set Identify the active setOPENOPEN Load the current row into variables Load the current row into variablesFETCHFETCH Test for existing rows Test for existing rows EMPTY? Return to FETCH if rows found Return to FETCH if rows found No Release the active set Release the active setCLOSECLOSEYes

16 16 Controlling Explicit Cursors Open the cursor. Cursor Pointer Fetch a row from the cursor. Cursor Pointer Continue until empty. Cursor Pointer Close the cursor.

17 17 Declaring the Cursor Syntax Syntax Do not include the INTO clause in the cursor declaration. Do not include the INTO clause in the cursor declaration. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. Syntax Syntax Do not include the INTO clause in the cursor declaration. Do not include the INTO clause in the cursor declaration. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. If processing rows in a specific sequence is required, use the ORDER BY clause in the query. CURSOR cursor_name IS select_statement; CURSOR cursor_name IS select_statement;

18 18 Declaring the Cursor Example Example DECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp; CURSOR dept_cursor IS SELECT * FROM dept WHERE deptno = 10; BEGIN... DECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp; CURSOR dept_cursor IS SELECT * FROM dept WHERE deptno = 10; BEGIN...

19 19 Opening the Cursor Syntax Syntax Open the cursor to execute the query and identify the active set. Open the cursor to execute the query and identify the active set. If the query returns no rows, no exception is raised. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch. Use cursor attributes to test the outcome after a fetch. Syntax Syntax Open the cursor to execute the query and identify the active set. Open the cursor to execute the query and identify the active set. If the query returns no rows, no exception is raised. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch. Use cursor attributes to test the outcome after a fetch. OPENcursor_name;

20 20 Fetching Data from the Cursor Syntax Syntax Retrieve the current row values into variables. Retrieve the current row values into variables. Include the same number of variables. Include the same number of variables. Match each variable to correspond to the columns positionally. Match each variable to correspond to the columns positionally. Test to see if the cursor contains rows. Test to see if the cursor contains rows. The FETCH statement performs the following operations: The FETCH statement performs the following operations: 1. Advances the pointer to the next row in the active set. 2. Reads the data for the current row into the output PL/SQL variables. Syntax Syntax Retrieve the current row values into variables. Retrieve the current row values into variables. Include the same number of variables. Include the same number of variables. Match each variable to correspond to the columns positionally. Match each variable to correspond to the columns positionally. Test to see if the cursor contains rows. Test to see if the cursor contains rows. The FETCH statement performs the following operations: The FETCH statement performs the following operations: 1. Advances the pointer to the next row in the active set. 2. Reads the data for the current row into the output PL/SQL variables. FETCH cursor_name INTO[variable1, variable2,...] | record_name]; FETCH cursor_name INTO[variable1, variable2,...] | record_name];

21 21 Fetching Data from the Cursor Examples Examples Examples Examples FETCH emp_cursor INTO v_empno, v_ename;... OPEN defined_cursor; LOOP FETCH defined_cursor INTO defined_variables EXIT WHEN...;... -- Process the retrieved data... END;... OPEN defined_cursor; LOOP FETCH defined_cursor INTO defined_variables EXIT WHEN...;... -- Process the retrieved data... END;

22 22 Closing the Cursor Syntax Syntax Close the cursor after completing the processing of the rows. Close the cursor after completing the processing of the rows. Reopen the cursor, if required. Reopen the cursor, if required. Do not attempt to fetch data from a cursor once it has been closed. Do not attempt to fetch data from a cursor once it has been closed. The CLOSE statement releases the context area. The CLOSE statement releases the context area. Syntax Syntax Close the cursor after completing the processing of the rows. Close the cursor after completing the processing of the rows. Reopen the cursor, if required. Reopen the cursor, if required. Do not attempt to fetch data from a cursor once it has been closed. Do not attempt to fetch data from a cursor once it has been closed. The CLOSE statement releases the context area. The CLOSE statement releases the context area. CLOSEcursor_name;

23 23 Explicit Cursor Example SQL> DECLARE v_num emp.empno%TYPE; v_num emp.empno%TYPE; v_name emp.ename%TYPE; v_name emp.ename%TYPE; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; BEGIN BEGIN OPEN my_cursor; OPEN my_cursor; LOOP LOOP FETCH my_cursor INTO v_num,v_name; FETCH my_cursor INTO v_num,v_name; EXIT WHEN my_cursor%NOTFOUND; EXIT WHEN my_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name); DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name); END LOOP; END LOOP; CLOSE my_cursor; CLOSE my_cursor; END; END; / 7902 has the name FORD 7934 has the name MILLER

24 24 Explicit Cursor Attributes Obtain status information about a cursor. Obtain status information about a cursor. AttributeType Description %ISOPENBoolean Evaluates to TRUE if the cursor is open %NOTFOUNDBoolean Evaluates to TRUE if the most recent fetch does not return a row %FOUNDBoolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNTNumberEvaluates to the total number of rows returned so far

25 25 Controlling Multiple Fetches Process several rows from an explicit cursor using a loop. Process several rows from an explicit cursor using a loop. Fetch a row with each iteration. Fetch a row with each iteration. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use explicit cursor attributes to test the success of each fetch. Use explicit cursor attributes to test the success of each fetch. Process several rows from an explicit cursor using a loop. Process several rows from an explicit cursor using a loop. Fetch a row with each iteration. Fetch a row with each iteration. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. Use explicit cursor attributes to test the success of each fetch. Use explicit cursor attributes to test the success of each fetch.

26 26 The %ISOPEN Attribute Fetch rows only when the cursor is open. Fetch rows only when the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Example Example Fetch rows only when the cursor is open. Fetch rows only when the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Example Example IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor... IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor...

27 27 The %NOTFOUND and %ROWCOUNT Attributes Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. The value of %ROWCOUNT before fetching any row is NULL. The value of %ROWCOUNT before fetching any row is NULL. Use the %NOTFOUND cursor attribute to determine when to exit the loop. Use the %NOTFOUND cursor attribute to determine when to exit the loop. Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. The value of %ROWCOUNT before fetching any row is NULL. The value of %ROWCOUNT before fetching any row is NULL. Use the %NOTFOUND cursor attribute to determine when to exit the loop. Use the %NOTFOUND cursor attribute to determine when to exit the loop.

28 28 Explicit Cursor %ISOPEN Example SQL> DECLARE v_num emp.empno%TYPE; v_num emp.empno%TYPE; v_name emp.ename%TYPE; v_name emp.ename%TYPE; r BOOLEAN; r BOOLEAN; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; BEGIN BEGIN OPEN my_cursor; OPEN my_cursor; r:=my_cursor%ISOPEN; r:=my_cursor%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open statement'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open statement'); END IF; END IF;

29 29 Explicit Cursor %ISOPEN Example Cont. LOOP FETCH my_cursor INTO v_num,v_name; FETCH my_cursor INTO v_num,v_name; EXIT WHEN my_cursor%NOTFOUND; EXIT WHEN my_cursor%NOTFOUND; END LOOP; END LOOP; CLOSE my_cursor; CLOSE my_cursor; r:=my_cursor%ISOPEN; r:=my_cursor%ISOPEN; IF r THEN IF r THEN DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close statement'); ELSE ELSE DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close statement'); DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close statement'); END IF; END IF; END; END; / The Cursor is opened after the open statement The Cursor is closed after the close statement

30 30 Explicit Cursor %ROWCOUNT Example SQL> DECLARE v_name emp.ename%TYPE; v_name emp.ename%TYPE; r NUMBER; r NUMBER; c NUMBER:=1; c NUMBER:=1; CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900; CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900; BEGIN BEGIN OPEN my_cursor; OPEN my_cursor; LOOP LOOP FETCH my_cursor INTO v_name; FETCH my_cursor INTO v_name; EXIT WHEN my_cursor%NOTFOUND; EXIT WHEN my_cursor%NOTFOUND; r:=my_cursor%ROWCOUNT; r:=my_cursor%ROWCOUNT; DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' || r); DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' || r); c:=c+1; c:=c+1; END LOOP; END LOOP; CLOSE my_cursor; CLOSE my_cursor; END; END; / After fetch number 1 ROWCOUNT has the value 1 After fetch number 2 ROWCOUNT has the value 2

31 31 Cursors and Records Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Example Example Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Example Example DECLARE CURSOR emp_cursor IS SELECTempno, ename FROMemp; emp_recordemp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record;... DECLARE CURSOR emp_cursor IS SELECTempno, ename FROMemp; emp_recordemp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record;...

32 32 Syntax Syntax The cursor FOR loop is a shortcut to process explicit cursors. The cursor FOR loop is a shortcut to process explicit cursors. Implicit open, fetch, and close occur. Implicit open, fetch, and close occur. The record is implicitly declared. The record is implicitly declared. Syntax Syntax The cursor FOR loop is a shortcut to process explicit cursors. The cursor FOR loop is a shortcut to process explicit cursors. Implicit open, fetch, and close occur. Implicit open, fetch, and close occur. The record is implicitly declared. The record is implicitly declared. Cursor FOR Loops FOR record_name IN cursor_name LOOP statement1; statement2;... END LOOP; FOR record_name IN cursor_name LOOP statement1; statement2;... END LOOP;

33 33 Cursor FOR Loops Retrieve employees one by one until no more are left. Retrieve employees one by one until no more are left. Example Example Retrieve employees one by one until no more are left. Retrieve employees one by one until no more are left. Example Example DECLARE CURSOR emp_cursor IS SELECT ename, deptno FROM emp; BEGIN FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN... END LOOP; -- implicit close occurs END; DECLARE CURSOR emp_cursor IS SELECT ename, deptno FROM emp; BEGIN FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN... END LOOP; -- implicit close occurs END;

34 SummarySummary Cursor types: Cursor types: Implicit cursors: Used for all DML statements and single-row queries. Implicit cursors: Used for all DML statements and single-row queries. Explicit cursors: Used for queries of zero, one, or more rows. Explicit cursors: Used for queries of zero, one, or more rows. You can manipulate explicit cursors. You can manipulate explicit cursors. You can evaluate the cursor status by using cursor attributes. You can evaluate the cursor status by using cursor attributes. You can use cursor FOR loops. You can use cursor FOR loops. Cursor types: Cursor types: Implicit cursors: Used for all DML statements and single-row queries. Implicit cursors: Used for all DML statements and single-row queries. Explicit cursors: Used for queries of zero, one, or more rows. Explicit cursors: Used for queries of zero, one, or more rows. You can manipulate explicit cursors. You can manipulate explicit cursors. You can evaluate the cursor status by using cursor attributes. You can evaluate the cursor status by using cursor attributes. You can use cursor FOR loops. You can use cursor FOR loops.


Download ppt "1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two."

Similar presentations


Ads by Google