Oracle Bi Solutions

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Wednesday, 9 January 2013

Cursors

Posted on 10:58 by Unknown

 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



Once you've declared your cursor, the next step is to open the cursor.
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 purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that some type of operation can be performed on the data. After declaring and opening your cursor, the next step is to FETCH the rows from your cursor.
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 final step of working with cursors is to close the cursor once you have finished using it.
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



While dealing with cursors, you may need to determine the status of your cursor. The following is a list of the cursor attributes that you can use.
AttributeExplanation
%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.
Below is an example of how you might use the %NOTFOUND attribute.
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 Select For Update statement allows you to lock the records in the cursor result set. You are not required to make changes to the records in order to use this statement. The record locks are released when the next commit or rollback statement is issued.
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




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.
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



Question: In Oracle, I have a table called "wine" and a stored procedure that outputs a cursor based on the "wine" table.
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



Question: In PSQL, I want to declare a cursor within cursor. The second cursor should use a value from the first cursor in the "where clause". How can I do this?
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

  1. Ref_cursor is of type REF CURSOR declared in Package
  2. I will to pass a comma separated Numbers as a string
  3. This should be used in the query in the IN Clause
  4. Execute the Query and Return the Output as REF Cursor
Something similar to the following:
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.


Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in PL/SQL | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • [ODI] - Frequently Asked Questions (FAQ)
    Here is a list of FAQs about Oracle Data Integrator 1) What is Oracle Data Integrator (ODI)? 2) What is E-LT? 3) What components make up Ora...
  • Upper Function
    In Oracle/PLSQL, the  upper function  converts all letters in the specified string to uppercase. If there are characters in the string that ...
  • OBIEE 11g Hide/Show Sections based on Dashboard Prompt
    allow a user’s interaction to hide/show certain sections of a dashboard. In this particular case the user wanted to choose either ‘Quarterly...
  • OBIEE 11g not showing new dashboard in the drop down menu
    When creating New dashboard in  OBIEE 11g, I have faced with issue that dashboard name did not show up in drop down dashboard menu. 1. When ...
  • [OBIEE11g] - OBIEE Dashboard for Informatica Metadata Reporting
    The metadata that Informatica Power Center 8 retains in its repository can be exposed via OBIEE reports and dashboards. This metadata includ...
  • Data Modeling: Schema Generation Issue with ERwin Data Modeler 7.3
    We are using Computer Associate’s ERwin Data Modeler 7.3 for data modeling. In one of our engagements, we are pushing data model changes to ...
  • Informatica Powercenter Workflow Manager Repository Navigator docking float issue
    In case you’re also experiencing where your Repository Navigator is not dock or attached and it seems just floating within Workflow Manager ...
  • OBIEE 11g - State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 46118] Out of disk space. (HY000)
    Error Details Error Codes: AAD5E5X3:OPR4ONWY:U9IM8TAC Odbc driver returned an error (SQLFetchScroll). State: HY000. Code: 10058. [NQODBC] [S...
  • To_Char Function
    In Oracle/PLSQL, the  to_char function  converts a number or date to a string. Syntax The syntax for the  to_char function  is: to_char( val...
  • OBIEE 11g - Query Limit
    Query limit and number of minutes a query can run per physical layer database connection, follow the below steps. > Login to Repository u...

Categories

  • BI Publisher
  • DAC
  • DataWarehouse
  • Hyperion
  • Informatica
  • OBIEE
  • ODI
  • Oracle Applications EBS 12.1.3
  • Oracle Database
  • PL/SQL
  • SQL
  • Unix/Linux

Blog Archive

  • ▼  2013 (500)
    • ►  November (8)
    • ►  October (1)
    • ►  July (4)
    • ►  June (9)
    • ►  May (15)
    • ►  April (24)
    • ►  March (43)
    • ►  February (73)
    • ▼  January (323)
      • Uninstalling Obiee 11g instance on a linux red hat
      • OBIEE 11g not showing new dashboard in the drop d...
      • OBIEE11g Installation
      • Starting OBIEE 11g Services on Linux
      • OBIEE11g Timestamp differencess
      • DAC11g Installation on Windows Server 2008R2.
      • BI Apps 7.9.6.4 Installation in widows server 2008R2
      • [OBIEE11g] - Eventually succeeded, but encountered...
      • [OBIEE11g] - Blue Screen Error While Login With Bi...
      • [OBIEE11g] - No Log Found Error
      • [OBIEE11g] - Stream Closed Error when Click on cor...
      • OBIA 7.9.6.4 RPD And Catalog Shared
      • [OBIEE11g] - Destination Path too Long error while...
      • [OBIEE11G] - Lookup table is a new feature in obie...
      • [OBIEE11g] - Create Veriable in OBIEE11g.
      • [OBIEE11g] - Configuring LDAP Server to provide OB...
      • [OBIEE11g] - Authentication Failure in OBIEE 11g
      • [OBIEE11g] - Bing Map Integration with OBIEE 11g
      • [OBIEE11g] - OBIEE Dashboard for Informatica Metad...
      • Informatica PowerCenter Upgrading from Version 8.6...
      • Data Modeling: Schema Generation Issue with ERwin ...
      • [OBIEE11g] - DAC Reporting in OBIEE11g
      • [OBIEE11g] - Publisher 11g – Performance Monitorin...
      • [OBIEE11g] - Auto Start OBIEE 11g using Windows Se...
      • [OBIEE11g] - Upgrade OBIEE 11.1.1.5 To Latest Vers...
      • OBIEE11g - User Right Click Interaction Control w...
      • [OBIEE11g] - Customizing Prompts ‘All Column Value...
      • [OBIEE11g] - Choosing the Right OBIEE Visualization
      • OBIEE11g - 11.1.1.6 New Features
      • [OBIEE11g] - Certification with Siebel Marketing f...
      • [OBIEE11g] - Creating a Stacked Bar Chart.
      • [BI EE11g] – Managing Host Name Changes
      • [DAC] - Multi Source Loads With OBIA
      • [Informatica] - ERROR CODES: [CNX_53021 ],[DOM_100...
      • [Informatica] - Informatica PowerCenter Repository...
      • [Informatica] - Processing UNICODE Characters in I...
      • [Linux] - Unix/Linix Commands
      • [DAC] - Full Load Vs Incremental Load
      • [Informatica] - Installation of Informatica 9.0.1 ...
      • [Informatica] - SF_34004- Service initialization ...
      • [Oracle Database] - Linux OS and Oracle database S...
      • [Oracle Database] - Installion Oracle database11g ...
      • [Informatica] - RR_4053 : Row error occurred while...
      • [OBIEE11g] - Change the placement of currency name
      • [OBIEE11g] - Exception Occuring During OBIEE 11.1....
      • What is Indexing in a Database
      • [OBIEE11g] - Setting up OBIEE11g Admin Tool for OD...
      • [OBIEE11g] - Getting Top-N Sales Reps Using the TO...
      • [OBIEE11g] - Getting Top-N Sales Reps Using Result...
      • [OBIEE11g] - Getting Top-N Sales Reps for Year and...
      • [OBIEE11g] - Analyzing Sales for “N Years Top-10 S...
      • [OBIEE11g] - Drill Down to Sub Reports Passing Mul...
      • [OBIEE11g[ - Configuring BI Scheduler for iBots on...
      • [OBIEE 11g] - How Application Roles, Groups and Us...
      • [OBIEE11g] - Setting up Access Permissions to Repo...
      • [OBIEE11g] - Fixing Weblogic and bi_server1 startu...
      • [OBIEE11g] - Deleting and Re-Creating Users in We...
      • [OBIEE 11g] - Backup and Restore of OBIEE Filesyst...
      • [OBIEE11g] - Creating Effective Bar Graphs
      • [OBIEE] - Useful SQL statements in Business Intell...
      • [OBIEE11g] - Creating Dashboard Traversing Throug...
      • [OBIEE11g] - Database Connection Failure while cr...
      • [DAC] - Admin password recovery
      • [Oracle 11g] - Oracle Database 11g installation on...
      • [OBIEE11g] - Variables in Oracle OBIEE 11g
      • [OBIEE11g] - Installing OBIEE 11g on Linux Fedora 17
      • [OBIEE11g] - Table view Date Column controlled by...
      • [OBIEE11g] - Adding Tooltips and conditional colo...
      • [OBIEE11g] - Show top-N Sales Persons in BI Publi...
      • [OBIEE11g] - Creating Scrolling Ticker Views
      • [OBIEE11g] - Authentication first with LDAP then ...
      • [OBIEE11g] - Relocation of OBIEE MetaData Reposit...
      • [OBIEE11g] - Hierarchical Roll-Up and Individual T...
      • [OBIEE11g] - Creation of Sales Reps Hierarchy wit...
      • [OBIEE11g] - Using external table to Filter BI Ans...
      • [OBIEE11g] - Configuring of RPD deployed on Linux...
      • [OBIEE11g] - Configuring an ODBC DSN for the Oracl...
      • [ODI] - Frequently Asked Questions (FAQ)
      • [OBIA] - Oracle BI Applications - Frequently Asked...
      • [OBIEE 11g] - Maps - Frequently Asked Questions (FAQ)
      • [OBIEE11g] - The 11g Features You Maybe Didn't Know!
      • [OBIEE11g] - New Features with OBIEE 11.1.1.6
      • [OBIEE11g] - Dashboard Prompt - "Prompt User"
      • [OBIEE11g] - [46153] The configuration file (O:\us...
      • [Informatica] - Multiple Chart of Accounts Configu...
      • [OBIEE11g] - Customizing Pivot Table Error
      • [OBIEE11g] - How to get Month Start Date and Month...
      • [OBIEE11g] - How to get Week Start Date and Week E...
      • [OBIEE11g] - How to rename My Dashboard
      • Table Organization in OBAW (Oracle Business Analyt...
      • [OBIEE11g] Uninstall OBIEE 11g
      • [OBIEE11g] - Command Line Merging in OBIEE 10g/11g
      • BI Publisher report is showing incorrect date(Show...
      • [OBIEE11g] - Connectivity issue from OBIEE (in Sol...
      • [OBIEE 11g] - Installation on Red Hat Linux
      • [OBIEE11g] - Different ToolTip for different rows ...
      • [OBIEE11g] - Integrating OBIEE 11g with EPM worksp...
      • [DAC] Fail to create indices during DAC execution ...
      • [DAC] Oracle DAC issue in 64 Bit Machine
      • [OBIEE11g] Connection Pool Select Button is Disabl...
Powered by Blogger.

About Me

Unknown
View my complete profile