跨模式比较oracle中的表

时间:2015-04-28 22:49:58

标签: oracle plsql

下面是用于比较不同模式中的两个表的代码。

问题:比较两个模式,我能够得到“表匹配”输出,但不能得到“表不匹配”输出。

create or replace procedure comparesch2( src_cowner IN all_tables.owner%TYPE , tgt_cowner IN all_tables.owner%TYPE) IS
-- Source Cursor declaration 
cursor c_tbl_src IS
  SELECT table_name
   FROM 
    all_tables
     where
      owner = src_cowner;
-- Target Cursor declaration
cursor c_tbl_tgt IS
  SELECT table_name
   FROM 
    all_tables
     where
      owner = tgt_cowner;
 r_tbl_src c_tbl_src%ROWTYPE;
 r_tbl_tgt c_tbl_tgt%ROWTYPE;
begin
  open c_tbl_src;
   open c_tbl_tgt;
LOOP
   fetch c_tbl_src INTO r_tbl_src;
    EXIT WHEN c_tbl_src%NOTFOUND;
fetch c_tbl_tgt INTO r_tbl_tgt;
    EXIT WHEN c_tbl_tgt%NOTFOUND;
IF r_tbl_src.table_name != r_tbl_tgt.table_name THEN
    dbms_output.put_line ( ' Table Donot Match:'|| r_tbl_src.table_name);
 end if;
IF r_tbl_src.table_name = r_tbl_tgt.table_name THEN
   dbms_output.put_line ( ' Table  Match:'|| r_tbl_src.table_name);
end if;
  END LOOP;
CLOSE c_tbl_src;
CLOSE c_tbl_tgt;
END;

1 个答案:

答案 0 :(得分:1)

主要问题之一是比较NULL。最简单的解决方案是通过将大多数逻辑放在SQL而不是PL / SQL中来避免此问题:

create or replace procedure compare_sch2(src_cowner varchar2, tgt_cowner varchar2) is
begin
    for tables in
    (
        select
            case
                when count(*) = 1 then 'Table does not match: '||table_name
                when count(*) = 2 then 'Table matches: '||table_name
            end does_it_match
        from all_tables
        where owner in (src_cowner, tgt_cowner)
        group by table_name
        order by table_name
    ) loop
        dbms_output.put_line(tables.does_it_match);
    end loop;
end;
/

以下是一个示例:

create user schema1 identified by schema1;
create user schema2 identified by schema2;

create table schema1.on_both(a number);
create table schema2.on_both(a number);
create table schema1.on_1_only(a number);
create table schema2.on_2_only(a number);

grant select on schema1.on_both to jheller;
grant select on schema2.on_both to jheller;
grant select on schema1.on_1_only to jheller;
grant select on schema2.on_2_only to jheller;


begin
    compare_sch2('SCHEMA1', 'SCHEMA2');
end;
/

Output:

Table does not match: ON_1_ONLY
Table does not match: ON_2_ONLY
Table matches: ON_BOTH