/*
 * Title  : sch_tab_frag.sql
 * Author : EXADIME LLC
 * Created: 29-Jul-2017
 * Updated: 05-Oct-2023
 * Release: 1.0.0
 * Purpose: Shows table fragmentation for the given schema.
 * 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 80

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

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

column dummy     noprint
column sno       format 9999            heading "#"
column name      format a30             heading "Name"
column total     format 99,999,999,999  heading "Total"
column used      format 99,999,999,999  heading "Used"
column frag      format 99,999,999,999  heading "KBytes|Fragmentation"
column claim     format 999.99          heading "%|Reclaimable"

compute sum of total on report
compute sum of used  on report
compute sum of frag  on report

break on report

accept p_owner char prompt "Enter schema name: "
accept p_claim char prompt "Enter minimum reclaimable percent [20]: " default 20
accept p_order char prompt "Enter order by column {1|2|3|4|5|6} [asc|desc]: " default "5 desc"
accept p_rows  char prompt "Enter number of records to be displayed [10]: " default 10

spool &&rpt_dir/sch_tab_frag.rpt

select 
	row_number() over(order by &&p_order) sno,
	name,
	total,
	used,
	frag,
	claim
from (
	select 
		owner,
		table_name name,
		round((blocks*8),2) total,
		round((num_rows*avg_row_len/1024),2) used,
		(round((blocks*8),2) - round((num_rows*avg_row_len/1024),2)) frag, 
		((round((blocks * 8), 2) - round((num_rows * avg_row_len / 1024), 2)) / round((blocks * 8), 2)) * 100 - 10 claim
	from 
		dba_tables
	where 
		owner in upper('&&p_owner') 
	and	(round((blocks*8),2) > round((num_rows*avg_row_len/1024),2))
	order by 5 desc
) where 
	claim >= &&p_claim
and 	rownum <= &&p_rows
order by
	&&p_order
/

spool off;

clear columns

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
