       
declare
bid     alias for $1;
eid     alias for $2;
topn    alias for $3;
textstr text;
rec RECORD;
begin
-- Confirm snap IDs
PERFORM 1 from edb$snap where edb_id = bid;
if not found then
     raise exception 'Begin snapshot identifier % does not exist', bid::text;
END IF;
PERFORM 1 from edb$snap where edb_id = eid;
if not found then
     raise exception 'End snapshot identifier % does not exist', eid::text;
END IF;
textstr := 'ID   '||' '||rpad('USER',10,' ')||' '||rpad('WAIT NAME',30,' ')||' '||rpad('COUNT',5,' ')||
' '||rpad('TIME',12,' ')||' '||rpad('% WAIT SESS',10)||' '||'% WAIT ALL';
return next textstr;
textstr := '---------------------------------------------------------------------------------------------------';
return next textstr;
for rec in (select fv.backend_id,
        fv.usename,
        fv.wait_name,
        fv.waitcnt,
        fv.totwait,
        -- sw.sumwait, tw.twaits
        round(100* (fv.totwait/sw.sumwait),2) as pctwaitsess,
        round(100 *(fv.totwait/tw.twaits),2) as pctwaitall 
 from (
 select e.backend_id, 
          e.usename,
          e.wait_name,
          abs(e.wait_count - b.wait_count)  as waitcnt,   		 
          abs(e.total_wait_time - b.total_wait_time)  as totwait      
             from  edb$session_waits  as b
                    ,  edb$session_waits  as e
                  where b.edb_id              	= bid
                  and e.edb_id              	= eid
                  and b.dbname              	= e.dbname
                  and b.wait_name           	= e.wait_name
                  and b.backend_id 		= e.backend_id
                  and (b.total_wait_time > 0 or e.total_wait_time > 0)
              order by backend_id, totwait desc ) as fv , 
 	(select e2.backend_id,sum(abs(e2.total_wait_time-b2.total_wait_time)) as sumwait 
		from edb$session_waits b2,
                    edb$session_waits e2
		where b2.edb_id = bid 
                    and e2.edb_id = eid
                      and b2.backend_id = e2.backend_id
                      and b2.wait_name = e2.wait_name
            	group by e2.backend_id having sum(abs(e2.total_wait_time-b2.total_wait_time)) > 0 
                order by e2.backend_id 	) as sw  ,          
    (select sum(abs(e3.total_wait_time - b3.total_wait_time)) as twaits  
    		from edb$session_waits b3, edb$session_waits e3
 		where b3.edb_id = bid and e3.edb_id = eid
                and b3.backend_id = e3.backend_id
		and b3.wait_name = e3.wait_name) as tw
where fv.backend_id = sw.backend_id
        limit topn)  LOOP   
                                 
textstr := rec.backend_id||' '||rpad(rec.usename,10,' ')||' '||rpad(rec.wait_name,30,' ')||' '||
rpad(rec.waitcnt::text,5,' ')||' '||rpad(rec.totwait::text,12,' ')||' '||rpad(rec.pctwaitsess::text,10,' ')||' '||rec.pctwaitall;
return next textstr;
end loop;
return;
end;
 