Search code examples
databaseoracle-databaseplsqldevelopercreate-table

how to name the column same as records of column of another table in oracle


is it possible to name the columns of one table same as the records of another table's column while creating the first table?

Example

table1: test1 
id package1 package2 package3--->column names same as the records of another table


table 2: test2
 name --->column
 package1 --->record1 under name column
 package2 --->record2 under name column
 package3 --->record3 under name column

Solution

  • I would do it this way via dynamic SQL:

    -- Contains table definitions
    create table table_def
    (
      name varchar2(100) not null,
      col1 varchar2(100) not null,
      col2 varchar2(100) not null,
      col3 varchar2(100) not null,
      col4 varchar2(100) not null
    );
    
    -- PK to be sure all table names are different
    alter table table_def add constraint table_defs_pk primary key (name);
    
    insert into table_def values('test1', 'id', 'package1', 'package2', 'package3');
    insert into table_def values('test2', 'name', 'package1', 'package2', 'package3');
    
    -- Loop on table definitions to create tables
    declare
      myQuery varchar2(1000);
    begin
      for line in
      (
        select * from table_def
      )
      loop
        myQuery := 'create table ' || line.name || ' ('
                          || line.col1 || ' varchar2(100), '
                          || line.col2 || ' varchar2(100), '
                          || line.col3 || ' varchar2(100), '
                          || line.col4 || ' varchar2(100))';
        dbms_output.put_line(myQuery);
        execute immediate myQuery;
      end loop;
    end;
    /