-- 此脚本适用于
prompt
prompt 创建临时表gtt
declare 
    num number;
begin
    select count(1) into num from user_tables where table_name = upper('gtt') and temporary = 'Y';
    if num = 0 then
        execute immediate '
            create global temporary table eoda.gtt
            as 
            select * from scott.emp where 1=0
        ';
    end if;
end;
/
prompt 
prompt 插入数据到eoda.gtt
begin
    execute immediate 'truncate table eoda.gtt';
    insert into eoda.gtt select * from scott.emp;
end;
/

set autotrace traceonly explain;
select /*+ first_rows */ * from eoda.gtt;
select /*+ first_rows dynamic_sampling(gtt 2) */ * from eoda.gtt;
set autotrace off;

prompt
prompt 创建临时表scott.emp_dynamic
declare 
    num number;
begin
    select count(1) into num from all_tables where table_name = upper( 'emp_dynamic' ) and owner = upper('eoda');
    if num = 0 then
        execute immediate '
            create table eoda.emp_dynamic 
            as
            select * from scott.emp 
        ';
    end if;
end;
/


prompt
prompt 创建临时表eoda.gtt1、和eoda.gtt2
declare 
    num1 number;
    num2 number;
begin
    select count(1) into num1 from user_tables where table_name = upper( 'gtt1' ) and temporary = 'Y';
    select count(1) into num2 from user_tables where table_name = upper( 'gtt2' ) and temporary = 'Y';
    if num1 = 1 then
        execute immediate 'drop table eoda.gtt1';
    end if;
    if num2 = 1 then
        execute immediate 'drop table eoda.gtt2';
    end if;
    execute immediate '
        create global temporary table eoda.gtt1 ( x number ) 
        on commit preserve rows
    ';
    execute immediate '
        create global temporary table eoda.gtt2 ( x number ) 
        on commit delete rows
    ';
end;
/

prompt 
prompt 插入数据到eoda.gtt1 eoda.gtt2
begin
    execute immediate 'truncate table eoda.gtt1';
    execute immediate 'truncate table eoda.gtt2';
    insert into eoda.gtt1 select user_id from all_users;
    insert into eoda.gtt2 select user_id from all_users;
    commit;
    dbms_stats.gather_schema_stats ( user );
end;
/
 
select table_name,last_analyzed,num_rows from user_tables where table_name in ('GTT1','GTT2','EMP_DYNAMIC');

-- 这儿查询不到临时表的信息，这个脚本是在oracle 12c上面跑的，也可能是由于版本原因造成的
prompt 
prompt 插入数据到eoda.gtt2
begin
    execute immediate 'truncate table eoda.gtt2';
    insert into eoda.gtt2 select user_id from all_users;
    commit;
    dbms_stats.gather_schema_stats ( user, gather_temp=>TRUE );
end;
/
 
select table_name,last_analyzed,num_rows from user_tables where table_name in ('GTT1','GTT2','EMP_DYNAMIC');
