/*
 * Title  : top_pga_ses.sql
 * Author : EXADIME LLC
 * Created: 06-Jul-2017
 * Updated: 10-Feb-2010
 * Release: 1.0.0
 * Purpose: Shows details of top PGA consuming sessions.
 * 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 rownum		format 9999		heading "#"
column spid		format a10		heading "SPID"
column sid		format 9999		heading "SID"
column serial#		format 99999999		heading "Serial#"
column username		format a30		heading "User Name"
column machine		format a45		heading "Machine"
column program		format a30		heading "Program"
column sql_id		format a15		heading "SQL Id"
column status		format a10		heading "Status"
column pga		format 99,999,999,999	heading "KBytes|PGA"

accept p_top	prompt "Enter top rows [10]: " default 10;

spool &&rpt_dir/top_pga_ses.rpt

select
	rownum,
	spid,
	sid,
	serial#,
	username,
	substr(machine,1,45) "Machine",
	substr(program,1,25) "Program",
	sql_id,
	status,
	value/1024 "PGA"
from (
	select
		p.spid,
		s.sid,
		s.serial#,
		s.username,
		s.machine,
		s.program,
		s.sql_id,
		s.status,
		t.value
	from
		v$statname n,
		v$session s,
		v$sesstat t,
		v$process p
	where
		s.paddr=p.addr
	and	s.sid=t.sid
	and	n.statistic#=t.statistic#
	and	s.type='USER'
	and	s.username is not null
	and 	n.name='session pga memory'
	order by
		t.value desc
)
where
	rownum<=&&p_top
order by
	value desc;

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