Link to home
Start Free TrialLog in
Avatar of ccorrente
ccorrente

asked on

Merging Cursors in PL/SQL

Is there a way to merge two or more cursors together into a single cursor in Oracle 10g PL/SQL?

I have multiple cursors that contain thousands of records.  Each cursor has an ID that ties the data together.  I then want to merge all of the cursors into a single cursor so that I can then perform further processing on each record in the cursor.  

I need to do this in PL/SQL within Oralce 10g.

Any ideas?
Avatar of MohanKNair
MohanKNair

There is no direct way to merger cursors. However it is possible to open both cursors

declare
c1t c1%rowtype;
c2t c2%rowtype;
BEGIN
open c1;
open c2;
LOOP
fetch c1 into c1t;
--  code exit conditions here
fetch c2 into c2t;
--  code exit conditions here
-- program logic
END LOOP;
Hi ccorrente,

If the SQLs in the 2 cursors are actually quite similar, another possible way is to write another cursor that unions the SQL in the 2 cursor or have a SQL with the conditions that will satisfy both cursors. Take note of any difference in the colmns that is selected in the 2 cursors and you need to adjust this merge SQL according such that they will contain the same sets of columns.

UNION method:
(Select ..... ) UNION (Select ....)

Merge condition :
Select ..
FROM ...
WHERE (conditions from cursor1)
OR (conditions from cursor2)

Which method is workable would depend on the kind of SQL that you have in the cursor.

Cheers,
NicksonKoh
This depends on the SQL of your 2 cusors, can u give me a idea , how these sql look like?
ASKER CERTIFIED SOLUTION
Avatar of oleggold
oleggold
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
NOT ONLY THIS LOOKS MORE ELEGANT AS IT SEEMS TO ME ,THIS IS ALSO MUCH MORE EFFICIENT,INSTEAD OF FETCHING 1000 ROWS PER EACH CURSOR WITH 2 SELECTS AND UNION/MAY BE SOME NESTED LOOP JOIN ON THAT IT WILL FETCH ONLY THE FIRST SELECT + ONLY RELEVANT ROWS FOR THE SECOND SELECT.
Avatar of Biswaranjan Rath
But I would suggest gather the queries of the cursor and create a NEW cursor using those queries. The advantage of this will be: a) it is simple to understand b) easy to implement and to work with c) comparatively take less memory space.
And with cursor merging there are few limitations like: 1) Result cursor may have huge data since it will merge the other cursor data and have cartesian product. Evene if there is not cartesian product, still I assume the resultset will be huge. 2) merging will complicate the understanding. 3) it will be error-prone.

If you still want to go for merging, then there are a lot of ways as other friends mentioned above.