/*
 * Title  : sho_top_sql.sql
 * Author : EXADIME LLC
 * Created: 17-Aug-2021
 * Updated: 17-Aug-2021
 * Release: 1.0.0
 * Purpose: Shows top CPU consuming SQL.
 * History: N/A
 */

start oracle.ini

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

set linesize 150
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 sno			format 9999		heading "#"
column sql_id 			format a13 		heading 'SQL ID'
column sql_text			format a20 		heading 'SQL Text'
column module			format a25		heading "Module"
column cpu_time 		format 999,999,999.99	heading 'CPU|Time'
column elapsed_time 		format 999,999,999.99	heading	'Elapsed|Time'
column disk_reads 		format 999,999,999,999	heading 'Disk|Reads'
column buffer_gets 		format 999,999,999,999	heading	'Buffer|Gets'
column rows_processed 		format 999,999,999,999	heading 'Rows|Processed'

accept p_order char prompt "Enter order by column {4|5|6|7|8} [asc|desc] " default "4 desc"
accept p_rows  char prompt "Enter number of records to be displayed [10]: " default 10

spool &&rpt_dir/sho_top_sql.rpt

select 
	row_number() over(order by &&p_order) sno,
	sql_id,
	sql_text,
	module,
	cpu_time,
	elapsed_time,
	disk_reads,
	buffer_gets,
	rows_processed
from
	(
	   select 
		sql_id,
		substr(sql_text,0,20) sql_text,
		substr(module,0,25) module,
		round(cpu_time/1000000,2) cpu_time,
		round(elapsed_time/1000000,2) elapsed_time,
		disk_reads,
		buffer_gets,
		rows_processed
	    from 
		v$sqlarea
	    order by 
		&&p_order
	)
where 
	rownum<=&&p_rows
/

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 150
set long 80

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