Declare a Cursor
A cursor is a SELECT statement that is defined within the declaration section of your PLSQL code. We'll take a look at three different syntaxes for cursors.
Cursor without parameters (simplest)
The basic syntax for a cursor without parameters is:
CURSOR cursor_name IS SELECT_statement;
For example, you could define a cursor called c1 as below.
CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in;
The result set of this cursor is all course_numbers whose course_name matches the variable called name_in.
Below is a function that uses this cursor.
CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; END;
Cursor with parameters
The basic syntax for a cursor with parameters is:
CURSOR cursor_name (parameter_list) IS SELECT_statement;
For example, you could define a cursor called c2 as below.
CURSOR c2 (subject_id_in IN varchar2) IS SELECT course_number from courses_tbl where subject_id = subject_id_in;
The result set of this cursor is all course_numbers whose subject_id matches the subject_id passed to the cursor via the parameter.
Cursor with return clause
The basic syntax for a cursor with a return clause is:
CURSOR cursor_name RETURN field%ROWTYPE IS SELECT_statement;
For example, you could define a cursor called c3 as below.
CURSOR c3 RETURN courses_tbl%ROWTYPE IS SELECT * from courses_tbl where subject = 'Mathematics';
The result set of this cursor is all columns from the course_tbl where the subject is Mathematics.
OPEN Statement
The basic syntax to OPEN the cursor is:
OPEN cursor_name;For example, you could open a cursor called c1 with the following command:
OPEN c1;Below is a function that demonstrates how to use the OPEN statement:
CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; END;
FETCH Statement
The basic syntax for a FETCH statement is:
FETCH cursor_name INTO <list of variables>;For example, you could have a cursor defined as:
CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in;The command that would be used to fetch the data from this cursor is:
FETCH c1 into cnumber;This would fetch the first course_number into the variable called cnumber.
Below is a function that demonstrates how to use the FETCH statement.
CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; END;
CLOSE Statement
The basic syntax to CLOSE the cursor is:
CLOSE cursor_name;For example, you could close a cursor called c1 with the following command:
CLOSE c1;Below is a function that demonstrates how to use the CLOSE statement:
CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; END;
Cursor Attributes
Attribute | Explanation |
---|---|
%ISOPEN | - Returns TRUE if the cursor is open, FALSE if the cursor is closed. |
%FOUND | - Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.- Returns NULL if cursor is open, but fetch has not been executed. - Returns TRUE if a successful fetch has been executed. - Returns FALSE if no row was returned. |
%NOTFOUND | - Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.- Return NULL if cursor is open, but fetch has not been executed. - Returns FALSE if a successful fetch has been executed. - Returns TRUE if no row was returned. |
%ROWCOUNT | - Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.- Returns the number of rows fetched. - The ROWCOUNT attribute doesn't give the real row count until you have iterated through the entire cursor. In other words, you shouldn't rely on this attribute to tell you how many rows are in a cursor after it is opened. |
CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; end if; close c1; RETURN cnumber; END;
SELECT FOR UPDATE Statement
The syntax for the Select For Update is:
CURSOR cursor_name IS select_statement FOR UPDATE [of column_list] [NOWAIT];For example, you could use the Select For Update statement as follows:
CURSOR c1 IS SELECT course_number, instructor from courses_tbl FOR UPDATE of instructor;If you plan on updating or deleting records that have been referenced by a Select For Update statement, you can use the Where Current Of statement.
WHERE CURRENT OF Statement
The syntax for the Where Current Of statement is either:
UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name;OR
DELETE FROM table_name WHERE CURRENT OF cursor_name;The Where Current Of statement allows you to update or delete the record that was last fetched by the cursor.
Updating using the WHERE CURRENT OF Statement
Here is an example where we are updating records using the Where Current Of Statement:CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in FOR UPDATE of instructor; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; else UPDATE courses_tbl SET instructor = 'SMITH' WHERE CURRENT OF c1; COMMIT; end if; close c1; RETURN cnumber; END;
Deleting using the WHERE CURRENT OF Statement
Here is an example where we are deleting records using the Where Current Of Statement:CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 ) RETURN number IS cnumber number; CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in FOR UPDATE of instructor; BEGIN open c1; fetch c1 into cnumber; if c1%notfound then cnumber := 9999; else DELETE FROM courses_tbl WHERE CURRENT OF c1; COMMIT; end if; close c1; RETURN cnumber; END;
Examples
Procedure that outputs a dynamic PLSQL cursor
I've created an HTML Form where the user can enter any combination of three values to retrieve results from the "wine" table. My problem is that I need a general "select" statement that will work no matter what value(s), the user enters.
For Example
parameter_1= "Chianti"parameter_2= "10"
parameter_3= wasn't entered by the user but I have to use in the select statement. And this is my problem. How to initialize this parameter to get all rows for column3?
SELECT * FROM wine WHERE column1 = parameter_1 AND column2 = parameter_2 AND column3 = parameter_3;The output of my stored procedure must be a cursor.
Answer: To solve your problem, you will need to output a dynamic PLSQL cursor in Oracle.
Let's take a look at how we can do this. We've divided this process into 3 steps.
Step 1 - Table Definition
First, we need a table created in Oracle called "wine". Below is the create statement for the wine table.create table wine ( col1 varchar2(40), col2 varchar2(40), col3 varchar2(40) );We've made this table definition very simple, for demonstration purposes.
Step 2 - Create package
Next, we've created a package called "winepkg" that contains our cursor definition. This needs to be done so that we can use a cursor as an output parameter in our stored procedure.create or replace PACKAGE winepkg IS /* Define the REF CURSOR type. */ TYPE wine_type IS REF CURSOR RETURN wine%ROWTYPE; END winepkg;This cursor will accept all fields from the "wine" table.
Step 3 - Create stored procedure
Our final step is to create a stored procedure to return the cursor. It accepts three parameters (entered by the user on the HTML Form) and returns a cursor (c1) of type "wine_type" which was declared in Step 2.The procedure will determine the appropriate cursor to return, based on the value(s) that have been entered by the user (input parameters).
create or replace procedure find_wine2 (col1_in in varchar2, col2_in in varchar2, col3_in in varchar2, c1 out winepkg.wine_type) as BEGIN /* all columns were entered */ IF (length(col1_in) > 0) and (length(col2_in) > 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in and wine.col2 = col2_in and wine.col3 = col3_in; /* col1 and col2 were entered */ ELSIF (length(col1_in) > 0) and (length(col2_in) > 0) and (length(col3_in) = 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in and wine.col2 = col2_in; /* col1 and col3 were entered */ ELSIF (length(col1_in) > 0) and (length(col2_in) = 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in wine.col3 = col3_in; /* col2 and col3 where entered */ ELSIF (length(col1_in) = 0) and (length(col2_in) > 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col2 = col2_in and wine.col3 = col3_in; /* col1 was entered */ ELSIF (length(col1_in) > 0) and (length(col2_in) = 0) and (length(col3_in) = 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in; /* col2 was entered */ ELSIF (length(col1_in) = 0) and (length(col2_in) > 0) and (length(col3_in) = 0) THEN OPEN c1 FOR select * from wine where wine.col2 = col2_in; /* col3 was entered */ ELSIF (length(col1_in) = 0) and (length(col2_in) = 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col3 = col3_in; END IF; END find_wine2;
Cursor within a cursor
Answer: Below is an example of how to declare a cursor within a cursor.
In this example, we have a cursor called get_tables that retrieves the owner and table_name values. These values are then used in a second cursor called get_columns.
create or replace procedure MULTIPLE_CURSORS_PROC is v_owner varchar2(40); v_table_name varchar2(40); v_column_name varchar2(100); /* First cursor */ cursor get_tables is select distinct tbl.owner, tbl.table_name from all_tables tbl where tbl.owner = 'SYSTEM'; /* Second cursor */ cursor get_columns is select distinct col.column_name from all_tab_columns col where col.owner = v_owner and col.table_name = v_table_name; begin -- Open first cursor open get_tables; loop fetch get_tables into v_owner, v_table_name; -- Open second cursor open get_columns; loop fetch get_columns into v_column_name; end loop; close get_columns; end loop; close get_tables; EXCEPTION WHEN OTHERS THEN raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM); end MULTIPLE_CURSORS_PROC;The trick to declaring a cursor within a cursor is that you need to continue to open and close the second cursor each time a new record is retrieved from the first cursor. That way, the second cursor will use the new variable values from the first cursor.
Cursor with variable in an "IN CLAUSE"
Question: I'm trying to use a variable in an IN CLAUSE.
Assumptions & declarations
- Ref_cursor is of type REF CURSOR declared in Package
- I will to pass a comma separated Numbers as a string
- This should be used in the query in the IN Clause
- Execute the Query and Return the Output as REF Cursor
Create or Replace Function func_name (inNumbers in Varchar2) Return PackageName.ref_cursor As out_cursor PackageName.Ref_cursor; Begin Open out_cursor For Select * from Table_name where column_name in (inNumbers); Return out_cursor; End;I seem to be getting an error when I try the code above. How can I use a variable in an IN CLAUSE?
Answer: Unfortunately, there is no easy way to use a variable in an IN CLAUSE if the variable contains a list of items. We can, however, suggest two alternative options:
Option #1
Instead of creating a string variable that contains a list of numbers, you could try storing each value in a separate variable. For example:Create or Replace Function func_name Return PackageName.ref_cursor As out_cursor PackageName.Ref_cursor; v1 varchar(2); v2 varchar(2); v3 varchar(2); Begin v1 := '1'; v2 := '2'; v3 := '3'; Open out_cursor For Select * from Table_name where column_name in (v1, v2, v3); Return out_cursor; End;
Option #2
You could try storing your values in a table. Then use a sub-select to retrieve the values.For example:
Create or Replace Function func_name Return PackageName.ref_cursor As out_cursor PackageName.Ref_cursor; Begin Open out_cursor For Select * from Table_name where column_name in (select values from list_table); Return out_cursor; End;In this example, we've stored our list in a table called list_table.