This is one of a major brain-ache problem I faced while doing programming in Oracle PLSQL to achieve one of my serious task.
I need to write a procedure/function/anonymous-block that will fetch all the records from an unknown table, let's say MyUnknownTable. This unknown table name could be any table from my existing database. The thing is, using some decision logic, I am finding a table name dynamically and then passing to the below code (means MyUnknownTable will be any table name which I will decide as per my logic in some other code), and then the below code should fetch all the records from that table in output.
SET serveroutput ON;
DECLARE
rc_ SYS_REFCURSOR;
c_ NUMBER;
i_ NUMBER;
col_count_ NUMBER;
desc_tab_ DBMS_SQL.DESC_TAB;
table_header VARCHAR2(2000);
table_data VARCHAR2(2000);
l_rec **MyUnknownTable**%rowtype;
BEGIN
OPEN rc_ FOR 'SELECT * FROM **MyUnknownTable**';
LOOP
FETCH rc_ INTO l_rec;
EXIT WHEN l_rec%notfound;
dbms_output.put_line(**<All Columns from l_rec>**);
END LOOP;
rc_.CLOSE();
END;
My problem with above code is l_rec
.
I know this way is wrong and senseless, but in the above code I am defining l_rec
as **MyUnknownTable**%rowtype
, so that l_rec
will gain the same data structure as MyUknownTable and FETCH rc_ INTO l_rec
will work. I haven't found the way how to declare l_rec
dynamically so that this can be used with any unknown table which my code will pass to this code block.
I used my brain to its limit minus half, but couldn't get into the way 'HOW'.
I need help from the rest of the Universe with a big hope.
Even this question is unanswered in Oracle Support Community https://community.oracle.com/thread/1036107
Below is the original code for reference where I need to make the code to fetch the data:
SET serveroutput ON;
DECLARE
v_column_name VARCHAR2(100) := UPPER('CASE_ID');
v_column_value VARCHAR2(100) := '324735';
CURSOR table_names_cur
IS
SELECT DISTINCT table_name
FROM ALL_TAB_COLS
WHERE UPPER(column_name)=UPPER(v_column_name)
AND table_name NOT LIKE '%$%'
AND owner LIKE 'ARGUS_APP';
rc_ SYS_REFCURSOR;
c_ NUMBER;
i_ NUMBER;
col_count_ NUMBER;
desc_tab_ DBMS_SQL.DESC_TAB;
table_header VARCHAR2(2000);
table_data VARCHAR2(2000);
BEGIN
dbms_output.put_line ('Script Execution Started ..');
FOR c_table_name IN table_names_cur
LOOP
OPEN rc_ FOR 'SELECT * FROM ' || c_table_name.table_name || ' WHERE ' || v_column_name || ' = ' || v_column_value || '';
c_ := DBMS_SQL.to_cursor_number(rc_);
DBMS_SQL.DESCRIBE_COLUMNS(c_, col_count_, desc_tab_);
table_header:= 'XYZ';
FOR i_ IN 1..col_count_
LOOP
IF table_header = 'XYZ' THEN
table_header := desc_tab_(i_).col_name;
ELSE
table_header := table_header || '|' || desc_tab_(i_).col_name;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE(table_header);
/*
**Need to write code here to fetch data from rc_**
*/
DBMS_SQL.CLOSE_CURSOR(c_);
END LOOP;
dbms_output.put_line ('Script Execution Completed ..' );
END;
~ Ajit Singh Sachan