问题描述:
表一:ORDERS
表二:HIST_ORDERS
HIST_ORDERS是ORDERS的备份表,但是在ORDERS添加了某些列,此时需要在HIST_ORDERS添加相同的列,或者单纯是找出缺少的列
SET SERVEROUTPUT ON
SET DEFINE OFF
--put the log into file
SPOOL 2014-11-262.log
----1、ORDERS HIST_ORDERS
DECLARE
V_FROM_TABLE VARCHAR2(50) :='ORDERS';
V_TO_TABLE VARCHAR2(50):='HIST_ORDERS';
cursor crecord
is
select * from
(select * from user_tab_columns where table_name=V_FROM_TABLE)
where column_name not in
(select column_name from user_tab_columns where table_name=V_TO_TABLE);
col crecord%rowtype;
BEGIN
open crecord;
dbms_output.put_line('Start to alter table '||V_TO_TABLE||':');
fetch crecord into col;
while crecord%found loop
if(col.data_type='TIMESTAMP(6)') then
dbms_output.put_line('alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type);
execute immediate 'alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type;
elsif(col.data_type='NUMBER') then
if(nvl(col.data_precision,-1)=-1 and nvl(col.data_scale,-1)=-1) then
dbms_output.put_line('alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type);
execute immediate 'alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type;
else
dbms_output.put_line('alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type||'('||col.data_precision||','||col.data_scale||')');
execute immediate 'alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type||'('||col.data_precision||','||col.data_scale||')';
end if;
elsif(col.data_type='DATE') then
dbms_output.put_line('alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type);
execute immediate 'alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type;
elsif(col.data_type='VARCHAR2') then
dbms_output.put_line('alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type||'('||col.data_length||')');
execute immediate 'alter table '||V_TO_TABLE||' add '||col.column_name||' '||col.data_type||'('||col.data_length||')';
else
dbms_output.put_line('Fail to add the column '||col.column_name||' '||col.data_type);
dbms_output.put_line('You program have not handle this type!Please check!');
end if;
fetch crecord into col;
end loop;
close crecord;
END;
/