prompt
prompt 创建表eoda.parent
declare 
    parent_num   number;
    child_num    number;
begin
    select count(1) into parent_num from all_tables where table_name = upper ( 'parent' ) and owner = upper ( 'eoda' );
    select count(1) into child_num from all_tables where table_name = upper ( 'child' ) and owner = upper ( 'eoda' );
    if child_num = 1 then 
        execute immediate 'drop table eoda.child';
    end if;
    if parent_num = 1 then 
        execute immediate 'drop table eoda.parent';
    end if;
    execute immediate '
        create table eoda.parent 
        (
            pk    int    primary key 
        )
    ';
end;
/


prompt
prompt 创建表eoda.child
declare
    parent_num   number;
    child_num    number;
begin
    select count(1) into parent_num from all_tables where table_name = upper ( 'parent' ) and owner = upper ( 'eoda' );
    select count(1) into child_num from all_tables where table_name = upper ( 'child' ) and owner = upper ( 'eoda' );
    if parent_num = 1 then 
        if child_num = 1 then
            execute immediate 'drop table eoda.child';
        end if;
        execute immediate '
            create table eoda.child
            (
                fk    constraint    child_fk_parent 
                references  parent(pk) 
                deferrable 
                initially immediate 
            )
        ';
    end if;
end;
/

prompt
prompt 插入数据到eoda.parent 和 eoda.child 
begin 
    insert into eoda.parent values ( 1 );
    insert into eoda.child values ( 1 );
end;
/

prompt
prompt 跟新表eoda.parent
begin
    update eoda.parent set pk = 2;
exception
    when others then 
        dbms_output.put_line ( 'Error!!!' || sqlerrm );
        rollback;
end;
/

begin 
    dbms_output.put_line ( '设置deferrable选项' );
end;
/

set constraint eoda.child_fk_parent deferred;

prompt
prompt 跟新表eoda.parent
begin
    update eoda.parent set pk = 2;
exception
    when others then 
        dbms_output.put_line ( 'Error!!!' || sqlerrm );
        rollback;
end;
/

prompt
prompt  插入eoda.child
begin
    update eoda.child set pk = 2;
exception
    when others then 
        dbms_output.put_line ( 'Error!!!' || sqlerrm );
        rollback;
end;
/

set constraint eoda.child_fk_parent immediate;
