I have a table which has select queries and insert queries stored as varchars. I have to execute the select query and insert the result of the select query using the insert query using a procedure. Right now I'm executing immediate and bulk collecting the select query into a table of varchars.
After this, I go to each row of vartable and take the values and put it in the insert query. I have a number of pairs of select and insert queries for a number of tables. So this has to be done dynamically. My question is, is there a better way to store the result of the select query? other than using a table of varchar? Because the result set of the select query might have millions of records and this might cause a problem. Would using a nested table type and using EXTEND on it solve the problem?
PROCEDURE SEL_INS
AS
CURSOR C
IS
SELECT
SELEQRY SELQRY,
INSQUERY INSERTQRY,
cols COLS
FROM TAB1;
selqry VARCHAR2(1000);
insqry VARCHAR2(1000);
tab1 vartable:=vartable();
cols NUMBER;
BEGIN
tab1:=vartable(NULL);
FOR X IN C
LOOP
selqry:= X.SELQRY;
cols:=X.COLS;
EXECUTE immediate selqry bulk collect INTO tab1;
-- select statement is concatenated before executing. so that each index has one record
--with values separated by commas
--- a sample column in tab1 will have values like (abc,abc1,abc2)
FOR i IN 1..tab1.count
LOOP
insqry :=X.INSERTQRY;
--- insert query will have values like insert into tab2 values('abc,'abc1','abc2')
EXECUTE immediate insqry;
END LOOP;
END LOOP;
END SEL_INS;
vartable is a table of type varchars2(4000)
As given in comments you should try to rewrite your statement as
INSERT INTO ... SELECT .... Let's assume this is not possible for whatever reason. In this case you can use procedure as below:Note, this procedure presumes that all columns are
VARCHAR2data type (with max. length of 2000 chars). If you have other data types, then lineDBMS_SQL.DEFINE_COLUMN(cur, i, desctab(i).COL_NAME, 2000);must be extended likeIF desctab(c).col_type = 1 THEN ...Also, note
DBMS_SQL.EXECUTE_AND_FETCHwill fail unless your select returns exactly one row. If your query may return more than just one row you have to useSee Oracle Built-in Data Types to get the code number of each data type.