/*
 * Title  : cr_tab.sql
 * Author : EXADIME LLC
 * Created: 11-May-2023
 * Updated: 11-May-2023
 * Release: 1.0.0
 * Purpose: Generates table creation script for the given table.
 * History: N/A
 */

start oracle.ini

set echo off
set feedback off
set serverout on
set termout on

set linesize 200
set pagesize 0
set pause off
set long 100000

set heading off
set headsep on
set underline on
set colsep " "

set define on
set verify off
set escape off
set embedded on

set serveroutput on
execute dbms_output.enable(10000000);

accept p_owner prompt 'Enter owner name: '
accept p_table prompt 'Enter table name: '
accept p_option prompt 'Storage attributes? [true/false]: ' default true

BEGIN
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SEGMENT_ATTRIBUTES', &&p_option);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'STORAGE', &&p_option);
END;
/

spool &&tmp_dir/cr_tab.tmp

prompt set feedback on echo on
prompt spool &&rpt_dir/cr_tab.rpt
prompt 
prompt rem 0.Table.
 
select 
	dbms_metadata.get_ddl('TABLE',upper('&&p_table'),upper('&&p_owner')) 
from 
	dual;

prompt
prompt rem 1.Indexes.

select 
	dbms_metadata.get_ddl('INDEX',index_name,upper('&&p_owner'))
from 
	dba_indexes
where
	owner=upper('&&p_owner')
and	table_name = upper('&&p_table');

prompt
prompt rem 2.Grant table privileges.

select 
	'GRANT '|| privilege || ' ON '|| owner || '.' || table_name || ' TO ' || grantee ||';'
from 
	dba_tab_privs
where
	owner=upper('&&p_owner')
and	table_name = upper('&&p_table');

prompt
prompt spool off

spool off

prompt Run the script "&&tmp_dir/cr_tab.tmp" manually.
prompt

set embedded off
set escape off
set verify on
set define on

set colsep " "
set underline on
set headsep on
set heading on

set pause off
set pagesize 24
set linesize 80
set long 80

set termout on
set serverout off
set feedback on
set echo off
