简体   繁体   中英

Pass arbitrary rowtype as parameter

Let's say I have a FOR loop like this:

FOR recs IN (SELECT table1.col, table2.col FROM TabA table1, TabB table2) 
LOOP
    renderRec(recs);
END LOOP;

And I need to make a procedure like this:

PROCEDURE renderRec(inRec IN ????) AS ...

How would I define the "recs" parameter for renderRec(), since it's not like a simple table%rowtype etc?

As far i could understand your requirement, you wanted to pass all the records from the query (SELECT table1.col, table2.col FROM TabA table1, TabB table2) to your procedure renderRec and the problem you face is while running the resultset of the query in For Loop , you don't know what dataype should be passed to the procedure. Ofcourse others have suggested the use of refcursor which might be one way of doing. But i would go with another way by creating a object and then passing the object to the procedure . You will see that i am using BULK operation inplace of FOR LOOP which is the fastest and easiest way. See below and read my comments inline for understanding:

--Table Setup

create table tabA(col number);
/
insert into taba values(1);
insert into taba values(2);
insert into taba values(3);
/
create table tabB(col number);
/
insert into tabb values(11);
insert into tabb values(22);
insert into tabb values(33);

commit;

--Object created with columns same as of query resultset to hold the result

CREATE OR REPLACE Type rec is OBJECT
(
 col1 number,
 col2 number
);

--Created a table of Object to hold multiple resultset

Create or replace Type var_rec is table of rec ;
/

-Procedure which takes resultset of the query in 1 go and display it.

CREATE OR REPLACE PROCEDURE renderRec(inpt IN var_rec)
AS
BEGIN
  FOR rec IN 1..inpt.count
  LOOP
    --displaying the resultset got from the select query
    dbms_output.put_line(inpt(rec).col1 ||'--'||inpt(rec).col2 );
  END LOOP;
END;
/

--Anoymous block to pass on the values of the query to the procedure

DECLARE
  v_recs var_rec:=var_rec();
BEGIN
  SELECT rec(table1.col,
             table2.col) 
  bulk collect  INTO v_recs
  FROM TabA table1,
    TabB table2 ;

  --Passing the resultset of the above query to the procedure.
  renderRec(v_recs);
END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM