如何将列命名为与oracle中另一个表的列的记录相同

时间:2014-07-04 09:39:16

标签: database oracle plsqldeveloper create-table

是否可以将一个表的列命名为与记录相同的列 创建第一个表时另一个表的列?

实施例

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

1 个答案:

答案 0 :(得分:1)

我会通过动态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;
/