Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to insert random table into a temp table dynamically?

ronald_2017Jul 2 2024 — edited Jul 2 2024

Hello All,

I use Oracle 19c, is there a way to insert random table into a temp table dynamically?

There are 2 conditions.

1. All tables have only one varchar2 column and this column is the first column. The other column types are number.

2. A table has maximum 10 columns.

create table tab1
(
item_name varchar2(4000),
c1 number,
c2 number,
c3 number,
c4 number,
c5 number
);

create table tab2
(
product_name varchar2(4000),
price1 number,
price2 number,
price3 number,
price4 number,
price5 number,
price6 number,
price7 number,
price8 number,
price9 number
);

create table tab3
(
nm varchar2(4000),
num1 number,
num2 number
);

create global temporary table temp_tab(
c1 varchar2,
c2 number,
c3 number,
c4 number,
c5 number,
c6 number,
c7 number,
c8 number,
c9 number,
c10 number
);

declare
  v_cursor sys_refcursor;
  function dyn_query(p_name varchar2)
  return clob
  is
    v_query clob := 'select * from {TABLE_NAME}';
  begin
    return replace(v_query, '{TABLE_NAME}', p_name);
  end;

begin
  
  open v_cursor for dyn_query('tab1');
  /*insert tab1 to temp table*/
  close v_cursor;


  open v_cursor for dyn_query('tab2');
  /*insert tab2 to temp table*/
  close v_cursor;
  
  open v_cursor for dyn_query('tab3');
  /*insert tab3 to temp table*/
  close v_cursor;

end;

Thanks in advance

This post has been answered by Cookiemonster76 on Jul 2 2024
Jump to Answer
Comments
Post Details
Added on Jul 2 2024
5 comments
246 views