2014-07-04 55 views
0

是否有可能在創建第一個表時將一個表的列命名爲另一個表的列的記錄 ?如何命名與oracle中另一個表的列相同的列

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

我會通過動態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; 
/
+0

謝謝:)它的工作原理 – user3751229

相關問題