Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
50% found this document useful (2 votes)
518 views

Oracle Dba Scripts

The document describes scripts for analyzing and monitoring an Oracle database. It includes scripts to analyze the buffer cache, calculate the length of the dirty buffer write queue, and compare table high water marks to actual data sizes to identify tables needing rebuilds. The scripts generate additional SQL scripts and output reports.

Uploaded by

raniboi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
518 views

Oracle Dba Scripts

The document describes scripts for analyzing and monitoring an Oracle database. It includes scripts to analyze the buffer cache, calculate the length of the dirty buffer write queue, and compare table high water marks to actual data sizes to identify tables needing rebuilds. The scripts generate additional SQL scripts and output reports.

Uploaded by

raniboi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 153

-############################################################################### ### ########### --- %purpose: analyze table with estimate or compute, depending on table size, see sign(n)

--- use: any table less than 10 mb in total size has statistics computed -while tables larger than 10 mb have statistics estimated. sign(n) ==> if n < 0 the function returns -1 -if n = 0 the functions returns 0 if n > 0 the functions returns 1 --############################################# ##################################### ########### -set feed off; set pagesize 10 000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; se t verify off; spool compute_or_estimate.sql -select 'analyze table '||owner||'.' ||table_name||' '|| decode(sign(10485760 - initial_extent),1,'compute statistics ;', 'estimate statistics;') from sys.dba_tables where owner not in ('sys','syste m'); / -spool off; set feed on; @compute_or_estimate.sql -###################### ############################################################ ########### --- %pu rpose: buffer cache analysis - objects (analysis of v$cache) --- use: needs orac le dba access --################################################################ ################## ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan off; set verify off;

set termout on; column column column column bt kind cb name format format format format a29 a12 99990 a24 heading heading heading heading 'block type' 'object t ype' 'nr of blocks' 'object name' ttitle left 'buffer cache analysis - objects' skip 2 spool select buffer_cache_a nalysis_obj.log name, kind, decode (class#,0, 'free', 1, 'data index', 2, 'sort', 3, 'save undo', 4, 'seg header', 5, 'save undo sh', 6, 'freelist block', 'other') as bt, count (block#) as cb fro m v$cache group by name, kind, class# order by cb desc, name, kind / spool off; -############################################################################### ### ########### --- %purpose: buffer cache analysis - slot status (analysis of v $cache) --- use: needs oracle dba access --##################################### ############################################# ########### -set feed off; set pag esize 10000; set wrap off; set linesize 200; set heading on; set tab on; set sca n on; set verify off; set termout on; ttitle left 'buffer cache analysis - slot status' skip 2

spool buffer_cache_analysis_slots.log select decode (status, 'free', 'xcur', 'sc ur', 'cr', 'read', 'mrec', 'irec', count(*) "counts" from v$cache group by statu s 'free', 'inst excl', 'inst shar', 'cons read', 'disk read', 'med reco', 'ins r eco', 'other') "slot status", / spool off; -#################################################################### ############## ########### --- %purpose: calculate 'average length of the dirty buffer write queue' for performance tuning --- use: oracle dba --############### ################################################################### ########### -prompt ======================================================================== prompt this script lists the dirty queue length. the longer the queue length, p rompt the more trouble the dbwr is having keeping up. prompt prompt average leng th of the dirty buffer write queue: prompt prompt if this is larger than the val ue of: prompt prompt 1. (db_files * db_file_simultaneous_writes)/2 [calculation1] prompt prompt or prompt prompt 2. 1/4 of db_block_buffers [calculation-1] pro mpt prompt which ever is smaller and also there is a platform specific limit pro mpt on the write batch size (normally 1024 or 2048 buffers). if the average prom pt length of the dirty buffer write queue is larger than the value prompt calcul ated before, increase db_file_simultaneous_writes or db_files. prompt also check for disks that are doing many more ios than other disks. prompt =============== ========================================================= -column "write request length" format 999,999.99 -select (sum(decode(name,'db_files',value)) * sum(dec ode(name,'db_file_simultaneous_writes',value)))/2 "calculation-1" from v$system_ parameter

where name in ('db_files','db_file_simultaneous_writes'); -select (sum(decode(na me,'db_block_buffers',value)) / 4) "calculation-2" from v$system_parameter where name in ('db_block_buffers'); -select sum(decode(name,'summed dirty queue lengt h',value)) / sum(decode(name,'write requests',value)) "write request length" fro m v$sysstat where name in ( 'summed dirty queue length','write requests') and va lue > 0; -###################################################################### ############ ########### --- %purpose: circuits trough dispatcher to shared serv erprozess, mts und sharedserver --############################################## #################################### ########### --- das diagramm circuit zeigt di e virtuellen verbindung zur datenbank -- instance via dispatcher und shared serv erprozess, welcher den user -- process verarbeitet. --dispatcher statistics --das diagramm dispatcher zeigt die statistiken der dispatcher prozesse -- der daten bank instance. --actual mts-parameters --- select name, value -- from v$paramete r -- where name like '%mts%' or name like '%mts%'; --max. number of server-proce sses --- select * from v$mts -queue --- das diagramm queue zeigt die aktivit ten des multi-threaded servers. --##################################################### ############################# ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on;

set verify off; -ttitle left 'circuits trough dispatcher to shared serverprozess ' skip 2 select rawtohex(c.circuit),d.name,s.sid,s.serial#, c.status, c.queue,c. bytes from v$circuit c,v$dispatcher d, v$shared_server s1,v$session s where c.di spatcher = d.paddr(+) and c.server = s1.paddr(+) and c.saddr = s.saddr(+) order by c.circuit; ttitle left 'dispatcher statistics' skip 2 select name, status, ac cept, messages, bytes, idle, busy from v$dispatcher order by name; ttitle left ' processes actually waiting for a shared server' skip 2 select queued from v$queu e where type = 'common'; ttitle left 'activity of mts' skip 2 select rawtohex(pa ddr), type, queued, totalq, decode(totalq, 0, 0, wait/totalq/100) "totalq" from v$queue order by paddr; -####################################################### ########################### ########### --- %purpose: compare hw-mark which is s ay 20% larger than the actual data in the tables (ora7) --- this script lists al l of the tables specified by owner, -- where the high water mark is say 20% larg er than the actual -- data in the tables. -- this will indicate which tables req uire a rebuild. --- notes: --- this script generates another script(hwm_get_sql. lst), which -- it calls at the end. the hwm_get_sql.lst file is not deleted -- w hen it is finished. -- you do not need to run an analyze on the tables before ru nning -- this script --- the rowid format changed between oracle 7 and oracle 8. --################################ -this script is for oracle 7 only -######### #######################

--- author: john dixon, published on http://www.revealnet.com --################ ################################################################## ########### set echo off set heading off set pagesize 0 set feedback off set linesize 1000 s et trimspool on set wrap on set verify off rem get the variables accept table_ow ner char prompt 'enter the table owner: ' accept percentage_larger number defaul t 20 prompt 'enter the percentage larger threshold the hwm can be [default 20]: ' prompt this may take a while... rem set termout off rem spool hwm_get_sql.lst prompt set echo off prompt set heading off prompt set termout on prompt set veri fy off rem step 1 - first generate the script to calc hwm and data for each tabl e in schema. select 'select owner,segment_name,hwm,actual_data from'||chr(10)|| ' (select round((count(distinct substr(rowid,15,4)||'||chr(10)|| 'substr(rowid,1 ,8))+1)*'||vp.value/1024||'/1024) as actual_data from '||chr(10)|| ds.owner||'.' ||ds.segment_name||') ad,'||chr(10)|| '(select s.owner,s.segment_name,round(s.bl ocks*'||vp.value/1024||'/1024) as hwm '||chr(10)|| 'from dba_segments s, dba_tab les t where s.owner='''||ds.owner||''' '||chr(10)|| 'and s.segment_name='''||ds. segment_name||''' and t.owner=s.owner and t.table_name=s.segment_name) hw'||chr( 10)|| ' where hw.hwm>(ad.actual_data*&&percentage_larger/100)+ad.actual_data'|| ' and ad.actual_data >0;' from dba_segments ds, dba_tables dt, v$parameter vp wh ere ds.owner=upper('&&table_owner') and ds.segment_name=dt.table_name and ds.own er=dt.owner and vp.name='db_block_size' order by segment_name / spool off rem st ep 2 - now generate the output rem spool hwm.lst set termout on column owner for mat a10 heading owner column segment_name format a40

column hwm format 999,999,999 column actual_data format 999,999,999 prompt high water mark report - this will indicate tables that require rebuilding. prompt ow ner table hwm(mb) data(mb) start hwm_get_sql.lst rem spool off (hwm.lst) -###### ############################################################################ ### ######## --- %purpose: compare hw-mark which is say 20% larger than the actual d ata in the tables (ora8) --- this script lists all of the tables specified by ow ner, -- where the high water mark is say 20% larger than the actual -- data in t he tables. -- this will indicate which tables require a rebuild. --- notes: --this script generates another script(hwm_get_sql.lst), which -- it calls at the end. the hwm_get_sql.lst file is not deleted -- when it is finished. -- you do n ot need to run an analyze on the tables before running -- this script --- the ro wid format changed between oracle 7 and oracle 8. --############################ #### -this script is for oracle 8 only -################################ --- aut hor: john dixon, published on http://www.revealnet.com --####################### ########################################################### ########### -set ech o off set heading off set pagesize 0 set feedback off set linesize 1000 set trim spool on set wrap on set verify off rem get the variables accept table_owner cha r prompt 'enter the table owner: ' accept percentage_larger number default 20 pr ompt 'enter the percentage larger threshold the hwm can be [default 20]: ' promp t this may take a while... rem set termout off rem spool hwm_get_sql.lst

prompt prompt prompt prompt set set set set echo off heading off termout on verify off rem step 1 - first generate the script to calc hwm and data for each table in sc hema. select 'select owner,segment_name,hwm,actual_data from'||chr(10)|| ' (sele ct round((count(distinct '||chr(10)|| 'substr(rowid,1,15))+1)*'||vp.value/1024|| '/1024) as actual_data from '||chr(10)|| ds.owner||'.'||ds.segment_name||') ad,' ||chr(10)|| '(select s.owner,s.segment_name,round(s.blocks*'||vp.value/1024||'/1 024) as hwm '||chr(10)|| 'from dba_segments s, dba_tables t where s.owner='''||d s.owner||''' '||chr(10)|| 'and s.segment_name='''||ds.segment_name||''' and t.ow ner=s.owner and t.table_name=s.segment_name) hw'||chr(10)|| ' where hw.hwm>(ad.a ctual_data*&&percentage_larger/100)+ad.actual_data'|| ' and ad.actual_data >0;' from dba_segments ds, dba_tables dt, v$parameter vp where ds.owner=upper('&&tabl e_owner') and ds.segment_name=dt.table_name and ds.owner=dt.owner and vp.name='d b_block_size' order by segment_name / spool off rem step 2 - now generate the ou tput rem spool hwm.lst set termout on column owner format a10 heading owner colu mn segment_name format a40 column hwm format 999,999,999 column actual_data form at 999,999,999 prompt high water mark report - this will indicate tables that re quire rebuilding. prompt owner table hwm(mb) data(mb) start hwm_get_sql.lst rem spool off (hwm.lst) -########################################################### ####################### ########### --- %purpose: decode as a very effizient use of if-then-else --- use: decode(expr,search,result,default) -if expr is equal t o search, oracle returns result, -if no match is found, oracle returns default. --############################################################################## #### ########### --- quite slow is ....... --

select count(*), sum(sal) from emp where deptno = 10 and ename like 'smith%'; -s elect count(*), sum(sal) from emp where deptno = 30 and ename like 'smith%'; --.... the same result much more efficiently with decode --- remeber that null va lues are never included in, nor do they affect the -- outcome of, the count and sum functions -select count(decode(deptno,10,'*',null)) d10_count, count(decode( deptno,30,'*',null)) d30_count, sum(decode(deptno,10,sal,null)) d10_sal, sum(dec ode(deptno,30,sal,null)) d30_sal from emp where ename like 'smith%'; -########## ######################################################################## ####### #### --- %purpose: database trigger to implement an update cascade with oracle8i --- in oracle8i the referential integrity is checked in the -- trigger, therefo re there is no mutating problem. however -- there is one problem with the follow ing update: --- update dept set deptno = deptno + 10; --- this update will updat e all departments with deptno 10 -- to the already existing deptno 20, and trigg ers again -- this rows. now all rows with deptno 20 will be changed -- to 30 and again all rows with deptno 30 will be changed -- to 40 and so on and on ... fin ally all rows have -- deptno = 50 ! --- therefore it's not allowed to update to an existing -- primary key, if this primary key have any childs. --############# ##################################################################### ########## # -create or replace trigger scott.dept_emp_update after update on scott.dept re ferencing new as new old as old for each row declare edeptnoexists exception;

-- check if child table have child records with this new -- deptno, this is not allowed. cursor select from where rtemp curs_exists_deptno is 'x' emp deptno = : new.deptno; curs_exists_deptno%rowtype; begin if(:new.deptno <> :old.deptno) then open curs_exists_deptno; fetch curs_ex ists_deptno into rtemp; if (curs_exists_deptno%found) then close curs_exists_dep tno; raise edeptnoexists; end if; close curs_exists_deptno; update emp set deptn o = :new.deptno where deptno = :old.deptno; end if; exception when edeptnoexists then raise_application_error (-20102,'error: this primary key: ' ||to_char(:new .deptno)||' exists and has child rows in emp, this tiggers again an update and s o on ...'); end dept_emp_update; -############################################## #################################### ########### --- %purpose: date arithmetic w ith oracle (e.g. how to add 1 [sec] to a date ?) --you can add and subtract numb er constants as well as other dates -from dates. oracle interprets number consta nts in arithmetic date -expressions as numbers of days. for example, sysdate + 1 is tomorrow. -sysdate - 7 is one week ago. sysdate + (10/1440) is ten minutes f rom now. -subtracting the hiredate column of the emp table from sysdate returns -the number of days since each employee was hired. you cannot multiply -or divid e date values. oracle provides functions for many common date -operations. for e xample, the add_months function lets you add or subtract -months from a date. th e months_between function returns the number of -months between two dates. the f ractional portion of the result represents

-that portion of a 31-day month. --############################################# ##################################### ########### -set serveroutput on; declare olddate date; newdate date; begin olddate := to_date('31.12.1999:23:59:59','dd.m m.yyyy:hh24:mi:ss'); newdate := olddate + 1/86400; dbms_output.put_line( 'newdat e=' ||to_char(newdate,'dd.mm.yyyy:hh24:mi:ss'); end; / newdate=01.01.2000:00:00: 00 pl/sql procedure successfully completed. -################################### ############################################### ########### --- %purpose: disabl e all relational constraints on tables owned by the user that executes this scri pt --########################################################################### ####### ########### --- requires oracle 8.1 -----------------------------------------------------------------------------prompt prompt generating script to dis able the relational constraints... set set set set set set pagesize 0 feedback o ff termout off linesize 100 trimspool on wrap on spool disable_relational_constraints.lst.sql prompt prompt prompt prompt disabli ng relational constraints... select 'prompt ... disabling constraint '||constrai nt_name||' on table '|| table_name , 'alter table '||table_name||' disable const raint '||constraint_name||';' from user_constraints where constraint_type = 'r' / spool off set feedback on

set termout on spool disable_relational_constraints.log @disable_relational_cons traints.lst.sql spool off -##################################################### ############################# ########### --- %purpose: displays an ordered list of all non-index segments > 10 mb --########################################### ####################################### ########### -select substr(owner,1,12) " owner", substr(segment_name,1,30) "segment name", substr(segment_type,1,10) "seg type", substr(tablespace_name,1,15) "tablespace", round(bytes/1000000) mb from dba_segments where (bytes > 10000000) and (segment_type <> 'index') order by byt es / -########################################################################## ######## ########### --- %purpose: displays an ordered list of the indexes on a given table --################################################################## ################ ########### -set linesize 120 verify off select i.table_name "t able", i.index_name "index", i.uniqueness "type", c.column_position "n", c.colum n_name "column" from all_indexes i, all_ind_columns c where i.table_name like up per('&table') and i.owner = c.index_owner and i.index_name = c.index_name order by i.table_name, i.index_name, c.column_position / -############################ ###################################################### ###########

--- %purpose: displays database resource usage statistics (whole instance or ses sion) --######################################################################## ########## ########### -set serveroutput on size 100000 verify off feedback off -accept sid number default 0 prompt 'enter sid, or press return for system stats : ' accept interval number default 10 prompt 'time interval in seconds [10]: ' p rompt prompt statistic change prompt --------------; -declare max_statistic# num ber; current_second integer; type stats_table is table of number index by binary _integer; first_stat stats_table; second_stat stats_table; stat_name varchar2(64 ); stat_class number; begin select max(statistic#) into max_statistic# from v$st atname; current_second := to_number(to_char(sysdate,'sssss')); while to_number(t o_char(sysdate,'sssss')) = current_second loop null; end loop; current_second := to_number(to_char(sysdate,'sssss')); for i in 0 .. max_statistic# loop if &&sid = 0 then select value into first_stat(i) from v$sysstat v where v.statistic# = i; else select value into first_stat(i) from v$sesstat v where v.sid = &&sid and v.statistic# = i; end if; end loop; while to_number(to_char(sysdate,'sssss')) < current_second + &&interval loop null; end loop; for i in 0 .. max_statistic# l oop if &&sid = 0 then select value into second_stat(i) from v$sysstat v where v. statistic# = i; else select value into second_stat(i) from v$sesstat v where v.s id = &&sid and v.statistic# = i; end if; end loop; for i in 0 .. max_statistic# loop if (second_stat(i) - first_stat(i)) > 0 then select v.name, v.class into st at_name, stat_class from v$statname v where v.statistic# = i;

if stat_class in (1,8,64,128) then dbms_output.put(rpad(stat_name,52)); dbms_out put.put_line( to_char(second_stat(i) first_stat(i),'9,999,990')); end if; end if ; end loop; end; / prompt undef sid interval set feedback on -################## ################################################################ ########### --%purpose: displays the execution plan for a sql dml statement --- the sql state ment should be in a separate text file, -- with either a ";" at the end of the l ine or a "/" on -- the next line. a plan_table table is required. --- usage: sql plus user/pwd @explain filename --############################################## #################################### ########### -set feedback off arraysize 10 trimspool on linesize 1000 -alter session set optimizer_percent_parallel = 100; -delete from plan_table; commit; -set echo on explain plan for @&1 set echo off -col "query plan" for a70 -select to_char(id,'999') id, to_char(parent_id,'999') pt, initcap( lpad(' ',2*(level-1)) || operation || ' ' || options || ' ' || dec ode(object_name,null,null,'of') || ' ' || object_name || ' ' || object_type || ' ' || decode(id,0,'cost = ' || ltrim(to_char(position,'999,999,999'))) ) "query plan", to_char(cardinality,'999,999,999') "row count", substr(initcap(other_tag) ,1,30) other from plan_table

start with id = 0 connect by prior id = parent_id / -rollback; -set feedback on -############################################################################### ### ########### --- %purpose: drop all objects of the user that executes this sc ript. --######################################################################## ########## ########### --- akadia sql utility scripts --- requires oracle 8.1 -----------------------------------------------------------------------------prom pt prompt generating script to drop the objects... set set set set set set pages ize 0 feedback off termout off linesize 100 trimspool on wrap on spool drop_user_objects.lst.sql prompt prompt prompt prompt dropping public syno nyms... select , from where / prompt prompt prompt prompt dropping relational co nstraints... select 'prompt ... dropping constraint '||constraint_name||' on tab le '|| table_name , 'alter table '||table_name||' drop constraint '||constraint_ name||';' from user_constraints where constraint_type = 'r' / prompt prompt prom pt prompt dropping remaining user objects... 'prompt ... dropping public synonym '||synonym_name 'drop public synonym '||synonym_name||';' all_synonyms table_ow ner = ( select user from dual )

select , from where / 'prompt ... dropping '||object_type||' '||object_name 'drop '||object_type||' '| |object_name||';' user_objects object_type != 'index' spool off set feedback on set termout on spool drop_user_objects.log @drop_user_ objects.lst.sql prompt prompt all database objects of the user dropped. prompt p lease review the log file drop_user_objects.log in the current directory. prompt prompt count of remaining objects: set feedback off select count(*) remaining_u ser_objects from user_objects / set feedback on spool off -##################### ############################################################# ########### --- %p urpose: enable all relational constraints on tables owned by the user that execu tes this script --############################################################## #################### ########### --- requires oracle 8.1 -----------------------------------------------------------------------------prompt prompt generating script to enable disabled relational constraints... set set set set set set page size 0 feedback off termout off linesize 100 trimspool on wrap on spool enable_relational_constraints.lst.sql prompt prompt prompt prompt enabling relational constraints... select 'prompt ... enabling constraint '||constraint_ name||' on table '|| table_name , 'alter table '||table_name||' enable constrain t '||constraint_name||';'

from where and / user_constraints constraint_type = 'r' status = 'disabled' spool off set feedback on set termout on spool enable_relational_constraints.log @enable_relational_constraints.lst.sql spool off -############################# ##################################################### ########### --- %purpose: extensive partitioning examples for oracle8 partition option --- example 1: - th e partition key is part of the primary key -- partition key: [date_cdr] -- prima ry key: [bkg_id,date_cdr] --- example 2: - the partition key is not part of the primary key -- partition key: [date_req] -- primary key: [bkg_id,req_id] --##### ############################################################################# ## ######### -drop table cdr cascade constraints; -create table cdr ( bkg_id number (15) not null, date_cdr date not null, calltype number(2) not null) partition by range (date_cdr) (partition cdr_01_1999 values less than (to_date('01.02.1999', 'dd.mm.yyyy')) tablespace cdr storage (initial 1k next 100m minextents 1 maxexte nts unlimited) pctfree 0, partition cdr_02_1999 values less than (to_date('01.03 .1999','dd.mm.yyyy')) tablespace cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_03_1999 values less than (to_date ('01.04.1999','dd.mm.yyyy')) tablespace cdr storage (initial 1k next 100m minext ents 1 maxextents unlimited) pctfree 0, partition cdr_04_1999 values less than ( to_date('01.05.1999','dd.mm.yyyy')) tablespace cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_05_1999 values less than (maxvalue) tablespace cdr storage (initial 1k next 100m minextents 1 maxex tents unlimited) pctfree 0) / ------------------------------------------------------------------- local non prefixed primary key (unique)

--- der linke teil des index stimmt nicht -- mit dem partition-key [date_cdr] ber ein ------------------------------------------------------------------alter tabl e cdr add ( constraint pk_cdr primary key (bkg_id,date_cdr) using index local (p artition cdr_01_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition cdr_02_1999 tablespace idx_cdr storag e (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition cdr _03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextent s unlimited) pctfree partition cdr_04_1999 tablespace idx_cdr storage (initial 1 k next 100m minextents 1 maxextents unlimited) pctfree partition cdr_05_1999 tab lespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree / --------------------------------------------------------------------local non prefixed key (non unique) --- der linke teil des index stimmt nicht - mit dem partition-key [date_cdr] berein -- der index kann nicht unique sein, da calltype nicht teil des -- primary keys ist. -----------------------------------------------------------------create index cdr_idx_1 on cdr (calltype) local ( partition cdr_01_1999 tablespace idx_cdr storage (initial 1k next 100m minextent s 1 maxextents unlimited) pctfree partition cdr_02_1999 tablespace idx_cdr stora ge (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition cd r_03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxexten ts unlimited) pctfree partition cdr_04_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition cdr_05_1999 ta blespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited ) pctfree / -------------------------------------------------------------------- local prefixed index (unique) --- der linke teil des index stimmt -- mit dem p artition-key [date_cdr] berein, deshalb kann der 0, 0, 0, 0, 0)) 0, 0, 0, 0, 0)

-- index unique sein. ------------------------------------------------------------------create unique index cdr_idx_2 on cdr (date_cdr,bkg_id) local (partition cdr_01_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxex tents unlimited) pctfree partition cdr_02_1999 tablespace idx_cdr storage (initi al 1k next 100m minextents 1 maxextents unlimited) pctfree partition cdr_03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimi ted) pctfree partition cdr_04_1999 tablespace idx_cdr storage (initial 1k next 1 00m minextents 1 maxextents unlimited) pctfree partition cdr_05_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree / alter table cdr add ( constraint cdr_idx_2 unique (date_cdr,bkg_id)) / -------------------------------------------------------------------- local prefixed i ndex (unique) --- der linke teil des index entspricht dem partition-key [date_cd r]. -- deshalb kann der index unique sein. ------------------------------------------------------------------create unique index cdr_idx_3 on cdr (date_cdr) lo cal (partition cdr_01_1999 tablespace idx_cdr storage (initial 1k next 100m mine xtents 1 maxextents unlimited) pctfree partition cdr_02_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partiti on cdr_03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 max extents unlimited) pctfree partition cdr_04_1999 tablespace idx_cdr storage (ini tial 1k next 100m minextents 1 maxextents unlimited) pctfree partition cdr_05_19 99 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unli mited) pctfree / ------------------------------------------------------------------- example 2: - der partition key ist nicht teil des primary keys -- partitio n key: [date_req] -- primary key: [bkg_id,req_id] ------------------------------------------------------------------drop table req cascade constraints; 0, 0, 0, 0, 0) 0, 0, 0, 0, 0)

-create table req ( bkg_id number(15) not null, req_id number(15) not null, date _req date not null, status number(2) not null) partition by range (date_req) (pa rtition req_01_1999 values less than (to_date('01.02.1999','dd.mm.yyyy')) tables pace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfre e partition req_02_1999 values less than (to_date('01.03.1999','dd.mm.yyyy')) ta blespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pc tfree partition req_03_1999 values less than (to_date('01.04.1999','dd.mm.yyyy') ) tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited ) pctfree partition req_04_1999 values less than (to_date('01.05.1999','dd.mm.yy yy')) tablespace req storage (initial 1k next 100m minextents 1 maxextents unlim ited) pctfree partition req_05_1999 values less than (maxvalue) tablespace req s torage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree / ------------------------------------------------------------------- normaler primary key, unpartitioniert, nicht zu empfehlen -- da der index wieder sehr gross wird. besser nach einem anderen -- kriterium partionieren, zb [bkg_id,req_id] ------------------------------------------------------------------alter table req add ( constraint pk_req primary key (bkg_id,req_id) using index tablespace idx_req s torage (initial 500k next 500k minextents 1 maxextents unlimited pctincrease 0 f reelists 2) ) / alter table req drop primary key / ------------------------------------------------------------------- globaler primary key, ein "must" f r Prima ry keys welche ohne -- den partition-key auskommen m ssen. ------------------------------------------------------------------create unique index pk_req on req (b kg_id,req_id) global partition by range (bkg_id,req_id) (partition pk_req_01 0, 0, 0, 0, 0)

1 maxextents unlimited) pctfree / alter table req add ( constraint pk_req primar y key (bkg_id,req_id)) / ------------------------------------------------------------------- local prefixed index (unique w re m glich) --- der linke teil des inde x stimmt mit dem partition-key -- [date_req] berein. ------------------------------------------------------------------create index idx_req_1 on req (date_req,r eq_id) local (partition req_01_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition req_02_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfre e partition req_03_1999 tablespace idx_req storage (initial 1k next 100m minexte nts 1 maxextents unlimited) pctfree partition req_04_1999 tablespace idx_req sto rage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition req_05_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxext ents unlimited) pctfree / ------------------------------------------------------------------- local prefixed index nur auf partition-key --- der index entspric ht mit dem partition-key [date_req] ------------------------------------------------------------------create index idx_req_2 on req (date_req) local (partition req_01_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxex tents unlimited) pctfree partition req_02_1999 tablespace idx_req values less than (100000,100000) tablespace idx_bkg storage (initial 1k next 100 m minextents partition pk_req_02 values less than (200000,200000) tablespace idx _bkg storage (initial 1k next 100m minextents partition pk_req_03 values less th an (300000,300000) tablespace idx_bkg storage (initial 1k next 100m minextents p artition pk_req_04 values less than (maxvalue,maxvalue) tablespace idx_bkg stora ge (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, 1 maxextents unlimited) pctfree 0, 1 maxextents unlimited) pctfree 0, 0) 0, 0, 0, 0, 0) 0,

100m minextents 1 maxextents unlimited) pctfree / ------------------------------------------------------------------- local non prefixed index --- der linke te il des index stimmt nicht mit dem -- partition-key date_req berein ------------------------------------------------------------------create index idx_req_3 on r eq (req_id,date_req) local (partition req_01_1999 tablespace idx_req storage (in itial 1k next 100m minextents 1 maxextents unlimited) pctfree partition req_02_1 999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unl imited) pctfree partition req_03_1999 tablespace idx_req storage (initial 1k nex t 100m minextents 1 maxextents unlimited) pctfree partition req_04_1999 tablespa ce idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctf ree partition req_05_1999 tablespace idx_req storage (initial 1k next 100m minex tents 1 maxextents unlimited) pctfree / ------------------------------------------------------------------- local non prefixed index --- der index ist ein beli ebiges attribut ------------------------------------------------------------------create index idx_req_4 on req (req_id) local (partition req_01_1999 tablespac e idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfr ee partition req_02_1999 tablespace idx_req storage (initial 1k next 100m minext ents 1 maxextents unlimited) pctfree partition req_03_1999 tablespace idx_req st orage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition req_04_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxex tents unlimited) pctfree partition req_05_1999 tablespace idx_req storage (initial 1k next partition req_03_1999 tablespace idx_req storage (initi al 1k next partition req_04_1999 tablespace idx_req storage (initial 1k next par tition req_05_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, 100m minextents 1 maxextents unlimited) pctfree 0, 100m minextents 1 maxextents unlimited) pctfree 0, 0) 0, 0, 0, 0, 0) 0, 0, 0, 0,

storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0) / ------------------------------------------------------------------- bitmapped ind exe --- bitmapped indexe sind immer local, global nicht m glich ------------------------------------------------------------------create bitmap index idx_bm_req_ 1 on req (status) local (partition req_01_1999 tablespace idx_req storage (initi al 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_02_1 999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unl imited) pctfree 0, partition req_03_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_04_1999 ta blespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited ) pctfree 0, partition req_05_1999 tablespace idx_req storage (initial 1k next 1 00m minextents 1 maxextents unlimited) pctfree 0) / ------------------------------------------------------------------- anf gen von zwei neuen partitionen ------------------------------------------------------------------alter table req spl it partition req_05_1999 at (to_date('31.05.1999','dd.mm.yyyy')) into (partition req_05_1999_1 tablespace req storage (initial 1k next 100m minextents 1 maxexte nts unlimited) pctfree partition req_05_1999_2 tablespace req storage (initial 1 k next 100m minextents 1 maxextents unlimited) pctfree / alter table req rename partition req_05_1999_1 to req_05_1999 / alter table req rename partition req_05 _1999_2 to req_06_1999 / -alter table req split partition req_06_1999 at (to_dat e('30.06.1999','dd.mm.yyyy')) into (partition req_06_1999_1 tablespace req stora ge (initial 1k next 100m minextents 1 maxextents unlimited) pctfree partition re q_06_1999_2 tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree / -0, 0) 0, 0)

-- die local indexes wurden auch aufgeteilt und m ssen -- nun wieder auf die gleic hen partionsnamen ge ndert werden -alter table req rename partition req_06_1999_1 to req_06_1999 / alter table req rename partition req_06_1999_2 to req_07_1999 / -alter index idx_req_1 rename partition req_05_1999_1 to req_05_1999 / alter in dex idx_req_1 rename partition req_06_1999_1 to req_06_1999 / alter index idx_re q_1 rename partition req_06_1999_2 to req_07_1999 / -alter index idx_req_2 renam e partition req_05_1999_1 to req_05_1999 / alter index idx_req_2 rename partitio n req_06_1999_1 to req_06_1999 / alter index idx_req_2 rename partition req_06_1 999_2 to req_07_1999 / -alter index idx_req_3 rename partition req_05_1999_1 to req_05_1999 / alter index idx_req_3 rename partition req_06_1999_1 to req_06_199 9 / alter index idx_req_3 rename partition req_06_1999_2 to req_07_1999 / -alter index idx_req_4 rename partition req_05_1999_1 to req_05_1999 / alter index idx _req_4 rename partition req_06_1999_1 to req_06_1999 / alter index idx_req_4 ren ame partition req_06_1999_2 to req_07_1999 / -alter index idx_bm_req_1 rename pa rtition req_05_1999_1 to req_05_1999 / alter index idx_bm_req_1 rename partition req_06_1999_1 to req_06_1999 / alter index idx_bm_req_1 rename partition req_06 _1999_2 to req_07_1999

/ --- rebuild aller local indexes -alter table req modify partition req_01_1999 rebuild unusable local indexes / alter table req modify partition req_02_1999 re build unusable local indexes / alter table req modify partition req_03_1999 rebu ild unusable local indexes / alter table req modify partition req_04_1999 rebuil d unusable local indexes / alter table req modify partition req_05_1999 rebuild unusable local indexes / alter table req modify partition req_06_1999 rebuild un usable local indexes / alter table req modify partition req_07_1999 rebuild unus able local indexes / ------------------------------------------------------------------- anf gen von einer neuen partition f r den primary key ------------------------------------------------------------------alter index pk_req split partitio n pk_req_04 at (400000,400000) into (partition pk_req_04_1 tablespace req storag e (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition pk_req_04_2 tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0) / alter index pk_req rename partition pk_req_04_1 to pk_r eq_04 / alter index pk_req rename partition pk_req_04_2 to pk_req_05 / --- rebui ld des primary keys einzeln f r jede partition -alter index pk_req rebuild partiti on pk_req_01 / alter index pk_req rebuild partition pk_req_02 / alter index pk_r eq rebuild partition pk_req_03 / alter index pk_req

rebuild partition pk_req_04 / alter index pk_req rebuild partition pk_req_05 / -- add partition (der partition key ist teil des primary keys) --- dies ist nur m glich, wenn die letzte partition nicht -- durch maxvalue begrenzt ist. deshalb l s chen wir die -- letzte partition zuerst. die local indexes werden beim -- hinzuf g en von partitions automatisch auch mit einer -- indexpartition erg nzt (sehr gute wartbarkeit). -alter table cdr drop partition cdr_05_1999; alter table cdr add p artition cdr_05_1999 values less than (to_date('01.06.1999','dd.mm.yyyy')) table space cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfr ee 0; alter table cdr add partition cdr_06_1999 values less than (to_date('01.07 .1999','dd.mm.yyyy')) tablespace cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0; alter table cdr add partition cdr_07_1999 value s less than (to_date('01.08.1999','dd.mm.yyyy')) tablespace cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0; --- add partition (d er partition key ist nicht teil des primary keys) --- auch hier werden die local indexes automatisch nachgefahren. -- die indexpartition des global primary key bleibt logischerweise -- unber hrt, da dies eine vollkommen autonome partition ist . -alter table req drop partition req_07_1999; alter table req add partition req _07_1999 values less than (to_date('01.08.1999','dd.mm.yyyy')) tablespace req st orage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0; alter table req add partition req_08_1999 values less than (to_date('01.09.1999','dd.m m.yyyy')) tablespace req storage (initial 1k next 100m minextents 1 maxextents u nlimited) pctfree 0; --- move partition -alter table req move partition req_08_1 999 tablespace tab storage (initial 1k next 1k minextents 1 maxextents unlimited ) pctfree 0; --- indexe m ssen rebuilded werden, da sie durch move

-- partition iu wurden (index unusable) -alter index idx_req_1 rebuild partition req_08_1999 / alter index idx_req_2 rebuild partition req_08_1999 / alter index idx_req_3 rebuild partition req_08_1999 / alter index idx_req_4 rebuild partiti on req_08_1999 / -############################################################## #################### ########### --- %purpose: flush shared pool when it reaches 60-70% of it's capacity --- use: sys-user --################################### ############################################### ########### --- on a recent proj ect we had a problem where performance would start -- acceptable at the beginnin g of the day and by mid-day would be -- totally unacceptable. investigation show ed that the third party -- application that ran on top of the oracle database wa s generating -- ad hoc sql without using bind variables. this generation of ad h oc -- sql and non-use of bind variables was resulting in proliferation of -- non -reusable code fragments in the shared pool, one user had over -- 90 shared pool segments assigned for queries that differed only by -- the selection parameter (for example "where last_name='smith'" -- instead of "where last_name='jones'"). this proliferation of multiple -- nearly identical sql statements meant that fo r each query issued -- the time to scan the shared pool for identical statements was increasing -- for each non-reusable statement generated. --- a flush of the shared pool was the only solution to solve this performance -- problem, resulti ng that all other query returned again in less than a second. --- it was determi ned that an automatic procedure was needed to monitor -- the shared pool and flu sh it when it reached 60-70% of capacity. --- the following procedue was created : -create or replace view sys.sql_summary as select username, sharable_mem, pers istent_mem, runtime_mem from sys.v_$sqlarea a, dba_users b where a.parsing_user_ id = b.user_id; create or replace procedure flush_it as

cursor get_share is select sum(sharable_mem) from sys.sql_summary; cursor select from where get_var is value v$sga name like 'var%'; cursor get_time is select sysdate from dual; todays_date mem_ratio share_mem var iable_mem cur sql_com row_proc begin open get_share; open get_var; fetch get_sha re into share_mem; dbms_output.put_line('share_mem: '||to_char(share_mem)); fetc h get_var into variable_mem; dbms_output.put_line('variable_mem: '||to_char(vari able_mem)); mem_ratio:=share_mem/variable_mem; dbms_output.put_line('mem_ratio: '||to_char(mem_ratio)); if (mem_ratio>0.3) then dbms_output.put_line ('flushing shared pool ...'); cur:=dbms_sql.open_cursor; sql_com:='alter system flush share d_pool'; dbms_sql.parse(cur,sql_com,dbms_sql.v7); row_proc:=dbms_sql.execute(cur ); dbms_sql.close_cursor(cur); end if; end; / -- this procedure was then loaded into the job queue and scheduled to run -- every hour using the following comman ds: declare job number; begin dbms_job.submit(job,'flush_it;',sysdate,'sysdate+1 /24'); end; / -################################################################# ################# date; number; number; number; integer; varchar2(60); number;

########### --- %purpose: formatted select * from 'table' statement results --sql script to display data from any table in a vertical layout -- and only 1 row per viewable page --- sample output for the emp table output format is : --- de pt = --------------------------crime [5] -- emp_no = ------------------------1 [ 1] -- first_name = --------------------john [4] -- join_date = --------------------02/01/1999 17:38:56 [9] -- last_name = ---------------------doe [3] -- middl e_initial = ----------------p [1] --- press return to continue --############### ################################################################### ########### col eol newline set head off pages 0 numf 9999999999.99 set lines 200 wrap on tr imspool on prompt note : long/raw/lob columns will not be displayed prompt set f eedback off verify off echo off accept tab prompt "enter table name: [example: e mp] " prompt prompt to enter strings in the where clause or order by, enclose it prompt within '''' single quotes instead of the usual single quote prompt [exam ple: ename = ''''james''''] prompt accept wher prompt "enter where clause {defau lt is none}: " accept oner prompt "enter owner {default is current user}: " acce pt sortorder prompt "enter order by clause <1,3,5,..> {default is unordered}: " prompt prompt press return ... prompt set termout off col column_name noprint co l wherstmt new_val wherclause col ordby new_val orderby col usr new_val objuser select decode(nvl(length('&sortorder'),0),0,'' ,' order by &sortorder') ordby , decode(nvl(length('&wher'),0),0,'' ,' where &wher') wherstmt , nvl(upper('&oner' ),user) usr from dual; spool vertdisp.sql select 'set pages '||to_char(count(*)+ 2) eol, 'set head off pause on numf 999999999999.99 lines 80 ' eol, 'set feedbac k off verify off echo off termout on trimspool on' eol from

dba_tab_columns where owner = '&objuser' and table_name = upper('&tab') and data _type not like ('%raw'); prompt select select column_name, 'rpad('||''''||column _name||' = '|| ''''||',33,'||''''||'-'||''''||') '||'||'|| decode(data_type,'dat e','to_char('||column_name||','||''''||'mm/dd/yyyy hh24:mi:ss'||''''||')', colum n_name) || ' '|| decode(data_type,'number',decode(sign(data_scale-1),-1,' ||', ' ||'),' '||' ||')|| ''''|| ' ['||''''||'||'|| ' to_char(nvl(length('||column_nam e||'),0))'|| '||'||''''||']'||''''||' eol,' cl from dba_tab_columns where owner = '&objuser' and table_name = upper('&tab') and data_type not like ('%raw') and column_name < (select max(column_name) from dba_tab_columns where owner = '&obju ser' and table_name = upper('&tab')) union select column_name, 'rpad('||''''||co lumn_name||' = '|| ''''||',33,'||''''||'-'||''''||') '||'||'|| decode(data_type, 'date','to_char('||column_name||','||''''||'mm/dd/yyyy hh24:mi:ss'||''''||')', c olumn_name) || ' '|| decode(data_type,'number',decode(sign(data_scale-1),-1,' || ', ' ||'),' '||' ||')|| ''''|| ' ['||''''||'||'|| ' to_char(nvl(length('||column _name||'),0))'|| '||'||''''||']'||''''||' eol'|| ' from &objuser..&tab '||' &whe rclause '||' &orderby ;' cl from dba_tab_columns where owner = '&objuser' and ta ble_name = upper('&tab') and data_type not like ('%raw') and column_name = (sele ct max(column_name ) from dba_tab_columns where owner = '&objuser' and table_nam e = upper('&tab')) order by column_name; spool off start vertdisp clear colu -## ################################################################################ ###########

--- %purpose: generate 'create table' script for an existing table in the databa se --- use: system, sys or user having select any table system privilege --##### ############################################################################# ## ######### -set serveroutput on size 200000 set echo off set feedback off set ver ify off set showmode off -accept l_user char prompt 'username: ' accept l_table char prompt 'tablename: ' -declare cursor tabcur is select table_name,owner,tabl espace_name, initial_extent,next_extent, pct_used,pct_free,pct_increase,degree f rom sys.dba_tables where owner=upper('&&l_user') and table_name=upper('&&l_table '); -cursor colcur(tablename varchar2) is select column_name col1, decode (data_ type, 'long', 'long ', 'long raw', 'long raw ', 'raw', 'raw ', 'date', 'date ', 'char', 'char' || '(' || data_length || ') ', 'varchar2', 'varchar2' || '(' || d ata_length || ') ', 'number', 'number' || decode (nvl(data_precision,0),0, ' ',' (' || data_precision || decode (nvl(data_scale, 0),0, ') ',',' || data_scale || ') '))) || decode (nullable,'n', 'not null',' ') col2 from sys.dba_tab_columns where table_name=tablename and owner=upper('&&l_user') order by column_id; -colc ount number(5); maxcol number(5); fillspace number(5); collen number(5); -begin maxcol:=0; -for tabrec in tabcur loop select max(column_id) into maxcol from sys .dba_tab_columns where table_name=tabrec.table_name and owner=tabrec.owner; --

dbms_output.put_line('create table '||tabrec.table_name); dbms_output.put_line(' ( '); -colcount:=0; for colrec in colcur(tabrec.table_name) loop collen:=length( colrec.col1); fillspace:=40 - collen; dbms_output.put(colrec.col1); -for i in 1. .fillspace loop dbms_output.put(' '); end loop; -dbms_output.put(colrec.col2); c olcount:=colcount+1; -if (colcount < maxcol) then dbms_output.put_line(','); els e dbms_output.put_line(')'); end if; end loop; -dbms_output.put_line('tablespace '||tabrec.tablespace_name); dbms_output.put_line('pctfree '||tabrec.pct_free); dbms_output.put_line('pctused '||tabrec.pct_used); dbms_output.put_line('storage ( '); dbms_output.put_line(' initial '||tabrec.initial_extent); dbms_output.put _line(' next '||tabrec.next_extent); dbms_output.put_line(' pctincrease '||tabre c.pct_increase); dbms_output.put_line(' )'); dbms_output.put_line('parallel '||t abrec.degree); dbms_output.put_line('/'); end loop; end; / -#################### ############################################################## ########### --- % purpose: generate insert statements for existing data in a table --- author: chr istoph.bohl@akadia.com --####################################################### ########################### ########### -prompt ================================ ========================================== prompt generate insert statements for existing data in a table prompt =============================================== =========================== prompt prompt you'll be prompted for the following: prompt - table_name: the name of the table to generate statements (case insensit ive) prompt - col1: the name of a column you want to fill with fixed data (case insensitive) prompt . - [enter]: do not use this functionality

prompt - col1_value: prompt . prompt . prompt - col2: insensitive) prompt . prom pt - col2_value: prompt . prompt . prompt set feedback off set trimspool on set linesize 255 the value for the column above (case sensitive) - enter string values within two single quotes: ''example'' - [enter]: do not use this functionality the name of a column you want to fill with fixed data (case - [enter]: do not use this func tionality the value for the column above (case sensitive) - enter string values within two single quotes: ''example'' - [enter]: do not use this functionality create or replace procedure genins(p_table in varchar ,p_default_col1 varchar de fault null ,p_default_col1_value varchar default null ,p_default_col2 varchar de fault null ,p_default_col2_value varchar default null) is -l_column_list varchar (2000); l_value_list varchar(2000); l_query varchar(2000); l_cursor integer; ign ore number; -function get_cols(p_table varchar) return varchar is l_cols varchar (2000); cursor l_col_cur(c_table varchar) is select column_name from user_tab_co lumns where table_name = upper(c_table) order by column_id; begin l_cols := null ; for rec in l_col_cur(p_table) loop l_cols := l_cols || rec.column_name || ','; end loop; return substr(l_cols,1,length(l_cols)-1); end; -function get_query(p_ table in varchar ,p_default_col1 varchar ,p_default_col1_value varchar ,p_defaul t_col2 varchar ,p_default_col2_value varchar) return varchar is l_query varchar( 2000); cursor l_query_cur(c_table varchar ,c_default_col1 varchar ,c_default_col 1_value varchar ,c_default_col2 varchar

,c_default_col2_value varchar) is select decode(column_name,c_default_col1,''''| | replace(c_default_col1_value,'''','''''')||'''', decode(column_name,c_default_ col2,''''|| replace(c_default_col2_value,'''','''''')||'''', 'decode('||column_n ame||',null,''null'','|| decode(data_type ,'varchar2','''''''''||'||column_name ||'||''''''''' ,'date' ,'''to_date(''''''||to_char('||column_name||',''yyyy-mmdd hh24:mi:ss'')||'''''',''''yyyy-mm-dd hh24:mi:ss'''')''' ,column_name ) || ')' ) ) column_query from user_tab_columns where table_name = upper(c_table) order by column_id; begin l_query := 'select '; for rec in l_query_cur(p_table, p_default _col1, p_default_col1_value, p_default_col2, p_default_col2_value) loop l_query := l_query || rec.column_query || '||'',''||'; end loop; l_query := substr(l_que ry,1,length(l_query)-7); return l_query || ' from ' || p_table; end; -begin l_co lumn_list := get_cols(p_table); l_query := get_query(p_table,upper(p_default_col 1),p_default_col1_value ,upper(p_default_col2),p_default_col2_value); l_cursor : = dbms_sql.open_cursor; dbms_sql.parse(l_cursor, l_query, dbms_sql.native); dbms _sql.define_column(l_cursor, 1, l_value_list, 2000); ignore := dbms_sql.execute( l_cursor); -loop if dbms_sql.fetch_rows(l_cursor)>0 then dbms_sql.column_value(l _cursor, 1, l_value_list); dbms_output.put_line('insert into '||p_table||' ('||l _column_list||')'); dbms_output.put_line(' values ('||l_value_list||');'); else exit; end if; end loop; end; / set serveroutput on size 1000000 exec genins('&ta ble_name','&col1','&col1_value','&col2','&col2_value'); set serveroutput off dro p procedure genins; set feedback on -########################################### ####################################### ########### --- %purpose: generate scrip t to coalesce free space in cluttered tablespaces

--############################################################################## #### ########### -select a1.tablespace_name,count(*) nbr_cont_wholes from sys.db a_free_space a1, sys.dba_free_space a2 where a1.tablespace_name=a2.tablespace_na me and a1.block_id+a1.blocks = a2.block_id group by a1.tablespace_name / set hea ding off spool alter_ts_coal.sql select 'alter tablespace '||a1.tablespace_name| |' coalesce;' from sys.dba_free_space a1, sys.dba_free_space a2 where a1.tablesp ace_name=a2.tablespace_name and a1.block_id+a1.blocks = a2.block_id group by a1. tablespace_name / spool off set heading on @alter_ts_coal.sql -################# ################################################################# ########### -- %purpose: guide for tuning the rollback segments --########################### ####################################################### ########### 1). size and number of waits per rollback-segment -----------------------------------------------select substr(rsn.name,1,10) "name", rss.rssize "tot-size [bytes]", rss.ex tents "extents", round(rss.rssize/rss.extents) "rs-size [bytes]", waits "number waits" from v$rollstat rss, v$rollname rsn where rss.usn = rsn.usn order by rsn. name; old tuning session: (rollback segments with 400 kb size) name tot-size [by tes] extents rs-size [bytes] number waits ---------- ---------------- ------------------------ -----------rbs01 8597504 21 409405 1616 rbs02 8597504 21 409405 4125 rbs03 8597504 21 409405 3992 rbs04 8597504 21 409405 4174 rbs05 8597504 21 409405 3617 rbs06 8597504 21 409405 3843 rbs07 8597504 21 409405 3715 rbs08 859 7504 21 409405 3730 rbs09 8597504 21 409405 25699 rbs10 8597504 21 409405 3635

new tuning session: (rollback segments with 5 mb size) name tot-size [bytes] ext ents rs-size [bytes] number waits ---------- ---------------- ---------- -------------- -----------rbs01 104853504 20 5242675 1715 rbs02 104853504 20 5242675 1 835 rbs03 104853504 20 5242675 1338 rbs04 104853504 20 5242675 1499 rbs05 104853 504 20 5242675 1572 rbs06 104853504 20 5242675 1628 rbs07 104853504 20 5242675 1 533 rbs08 104853504 20 5242675 1689 rbs09 104853504 20 5242675 1461 rbs10 104853 504 20 5242675 1663 2). rollback contention ----------------------select name,ge ts,waits, to_char(((gets-waits)*100)/gets,'999.9999') hit_ratio from v$rollstat s, v$rollname r where s.usn = r.usn order by r.name; old tuning session: (rollba ck segments with 400 kb size) name gets waits hit_ratio ----------------------------- ---------- ---------- --------rbs01 5314092 1643 99.9691 rbs02 10363748 4 157 99.9599 rbs03 10459920 4017 99.9616 rbs04 10962299 4184 99.9618 rbs05 946971 2 3649 99.9615 rbs06 10218019 3889 99.9619 rbs07 9796463 3736 99.9619 rbs08 9900 727 3739 99.9622 rbs09 13130819 25721 99.8041 rbs10 9456272 3673 99.9612 new tun ing session: (rollback segments with 5 mb size) name gets waits hit_ratio ----------------------------- ---------- ---------- --------rbs01 5837671 1719 99.970 6 rbs02 6151758 1835 99.9702 rbs03 5451355 1338 99.9755 rbs04 5105157 1499 99.97 06 rbs05 5333881 1574 99.9705 rbs06 6070279 1631 99.9731 rbs07 5611779 1533 99.9 727 rbs08 6097782 1692 99.9723 rbs09 5558601 1462 99.9737 rbs10 6418860 1663 99. 9741 3). compare rollback segment waits with total number of gets ----------------------------------------------------------rollback segment waits select v.cla ss, v.count

from v$waitstat v where class in ('system undo header','system undo block', 'und o header','undo block'); total number of gets select to_char(sum(value),'999,999 ,999,999') "total gets" from v$sysstat where name in ('db block gets','consisten t gets'); old tuning session: (much waits compared with total gets) class count ------------------ ---------system undo header 0 system undo block 0 undo header 74880 undo block 21618 total gets ---------------8,896,140,872 new tuning sessi on: (much waits compared with total gets, not better) class count ----------------- ---------system undo header 0 system undo block 0 undo header 24138 undo bl ock 28146 total gets ---------------4,152,462,130 4). overall system-statistics for all rollback-segments -----------------------------------------------------select statistic#,substr(name,1,50) "name", class,value from v$sysstat where nam e in ('user rollbacks', 'rollback changes - undo records applied', 'transaction rollbacks'); old tuning session statistic# name class value ---------- ------------------------------------------------- --------------------5 user rollbacks 1 30 113 rollback changes - undo records applied 128 2'524'864 114 transaction ro llbacks 128 29'131

a low number of rollbacks initiate a high nunber of waits ! new tuning session s tatistic# value ------------------5 51 113 111886 114 13649 name class -------------------------------------------------- ---------user rollbacks rollb ack changes - undo records applied transaction rollbacks 1 128 128 5). who uses the rollback segments ---------------------------------select r.usn ,substr(r.name,1,10) "name",s.osuser, substr(s.username,1,15) "user",s.sid,x.ext ents, x.extends,x.waits,x.shrinks, x.wraps from sys.v_$rollstat x, sys.v_$rollna me r, sys.v_$session s, sys.v_$transaction t where t.addr = s.taddr (+) and x.us n (+) = r.usn and t.xidusn (+) = r.usn order by r.usn; old tuning session usn na me extends waits ---------- ------------------- ---------0 system 0 0 2 rbs01 32 1 1703 3 rbs02 370 4175 4 rbs03 445 4074 5 rbs04 262 4252 6 rbs05 195 3772 7 rbs 06 291 4044 8 rbs07 259 3803 9 rbs08 529 3820 10 rbs09 599 25839 11 rbs10 osuser user sid extents shrinks wraps --------------- --------------- ---------- ------------------ ---------4 0 0 poseidon vp_link 55 21 34 3448 ota dispatcher 35 2 1 42 6589 poseidon vp_link 59 21 53 6981 poseidon vp_link 56 21 33 7073 bscs smh _link 76 21 22 5847 21 34 6665 21 31 6336 poseidon vp_link 57 21 64 6789 poseido n vp_link 54 21 69 8153 21

398 3772 45 5878 new tuning session usn name extends waits ---------- ------------------- --------0 system 0 0 1 rbs10 0 1681 2 rbs01 0 1731 3 rbs02 0 1850 4 rbs03 0 1338 5 rbs 04 0 1499 6 rbs05 0 1583 7 rbs06 0 1645 8 rbs07 0 1533 9 rbs08 0 1694 10 rbs09 0 1483 osuser user sid extents shrinks wraps --------------- --------------- --------- ------------------- ---------4 0 1 20 0 299 20 0 277 poseidon vp_link 93 20 0 288 poseidon vp_link 92 20 0 248 poseidon vp_link 86 20 0 232 bscs smh_link 94 20 0 258 bscs smh_link 113 20 0 282 poseidon vp_link 70 20 0 260 20 0 274 20 0 264 no more extends and shrinks. -################################################## ################################ ########### --- %purpose: guide for tuning with utlbstat und utlestat --####################################################### ########################### ########### *********************************** 1). select library cache statistics *********************************** the library cache is where oracle stores object definitions, sql statements etc. each namesp ace (or library) contains different types of object. the figures here give a qui ck summary of the usage of each namespace. the most useful indicator here is the reloads column. nearly no reloads, shared pool is ok. ************************* *** 2). cpu used by this session ****************************

by comparing the relative time spent waiting on each wait event and the cpu used by this session, we can see where the oracle instance is spending most of its t ime. statistic total per transact per logon per second -------------------------- ------------ ------------ ------------ -----------cpu used by this session 54 2660 1.18 2647.12 95.22 parse time cpu 244 0 1.19 .04 ************************** ********* 3). locating cpu-heavy sql (top 15) ********************************** * the statement below finds sql statements which access database buffers a lot. such statements are typically heavy on cpu usage because they are probably looki ng at a lot of rows of data: select disk_reads, buffer_gets, executions, buffer_ gets/executions "gets/exec", disk_reads/executions "reads/exec", round((buffer_g ets - disk_reads) / buffer_gets, 2) * 100 "hitratio", sql_text from v$sqlarea wh ere buffer_gets > 10000000 and executions > 1000000 order by buffer_gets desc; d isk-reads buffer-gets executions gets/exec reads/exec hitratio ---------- ---------- ---------- ---------- ---------- ---------14607 40882602 3211863 12.728625 7 .004547828 100 sql-text -------------------------------------------------------------------------update sscrequest set msgstate=:b1,response=:b2,servicestate =:b3,returncode =:b4,inipara=:b5,processtime=sysdate where requestid=:b6 disk-re ads buffer-gets executions gets/exec reads/exec hitratio ---------- -------------------- ---------- ---------- ---------188249 34923996 1528920 22.8422651 .12 3125474 99 sql-text -------------------------------------------------------------------------update sscorder set state=:b1,returncode=:b2,priority=:b3,processt ime=sysda te,deferred=to_date(:b4,'yyyymmddhh24miss')where requestid=:b5 ******* *************************************************** 4). locating cpu-heavy sessi ons (cpu used by this session) ************************************************* ********* select substr(a.sid,1,5) "sid", substr(a.process,1,7) "process", subst r(a.username,1,20) "user", v.value "cpu used by this session" from v$statname s, v$sesstat v, v$session a where s.name = 'cpu used by this session' and v.statis tic#=s.statistic# and v.sid = a.sid and v.value > 1000 order by v.value desc;

sid ----62 82 103 110 83 69 59 60 51 71 53 process ------12602 10949 12603 16629 9913 12430 12265 10997 16628 11017 12138 user cpu used by this session -------------------- -----------------------sscdsp 2791153 sscsmh 1591242 sscdsp 191758 dispatcher 50677 smh_link 48296 sscfsm 441 23 sscfsm 43812 sscfsm 43722 dispatcher 35865 sscsmh 33881 sscfsm 27938 ********************** 5). common wait events ********************** system wide wait events for non-background processes (pmon, smon, etc). times are in hundre ths of seconds. each one of these is a context switch which costs cpu time. by l ooking at the total time you can often determine what is the bottleneck that pro cesses are waiting for. this shows the total time spent waiting for a specific e vent and the average time per wait on that event. ignore any 'idle' wait events. common idle wait events include: client message sql*net message from client sql *net more data from client rdbms ipc message pipe get null event pmon timer smon timer parallel query dequeue - process waiting for data from the client applica tion usually background process waiting for work dbms_pipe read waiting for data miscellaneous pmon waiting for work smon waiting for work waiting for input (di scussed later) event name count total time avg time -------------------------------- ------------ ------------- ------------log file sync 527031 2076364 3.94 db file sequenti al read 379096 948531 2.5 write complete waits 1549 90879 58.67 db file scattere d read 508925 55312 .11 buffer busy waits 6070 44408 7.32 log file switch comple tion 276 13875 50.27 latch free 2828 5517 1.95 enqueue 284 2498 8.8 log buffer s pace 102 753 7.38 buffer deadlock 24 48 2 control file sequential read 134 16 .1 2 ----------------------------------------system wide waits for "buffer busy wai ts" ----------------------------------------this wait happens when a session wan ts to access a database block in the buffer cache but it cannot as the buffer is "busy". the two main cases where this can occur are:

- another session is reading the block into the buffer - another session holds t he buffer in an incompatible mode to our request if the time spent waiting for b uffers is significant then we need to determine which segment/s is/are suffering from contention. the "buffer busy wait statistics" section of the bstat/estat s hows which block type/s are seeing the most contention. this information is deri ved from the v$waitstat which can be queried in isolation. this shows the class of block with the most waits at the bottom of the list. select time, count, clas s from v$waitstat order by time,count; time count class ---------- ---------- ----------------0 0 sort block 0 0 save undo block 0 0 save undo header 0 0 free list 0 0 system undo block 0 0 system undo header 5812 442 segment header 506921 35983 undo block 561185 30039 undo header 922683 203757 data block additional i nformation can be obtained from the internal view x$kcbfwait thus: select from w here order count, file#, substr(name,1,50) x$kcbfwait, v$datafile indx + 1 = fil e# by count; count file# substr(name,1,50) ---------- ---------- ------------------------------------------------0 3 /data/ota/db1/otasicap/data/temp01.dbf 0 4 /data/ota/db 1/otasicap/data/users.dbf 0 16 /data/ota/db2/otasicap/data/idx_sccms_02.dbf 0 17 /data/ota/db1/otasicap/data/tbs_sccorder_03.dbf 0 5 /data/ota/db1/otasicap/data /tools.dbf 1 1 /data/ota/db1/otasicap/data/system01.dbf 9 13 /data/ota/db1/otasi cap/data/tbs_sccms_01.dbf 14 14 /data/ota/db1/otasicap/data/tbs_sccms_02.dbf 36 15 /data/ota/db2/otasicap/data/idx_sccms_01.dbf 52 12 /data/ota/db2/otasicap/dat a/idx_sccorder_03.dbf 1181 11 /data/ota/db2/otasicap/data/idx_sccorder_02.dbf 53 37 7 /data/ota/db2/otasicap/data/idx_01.dbf 6535 8 /data/ota/db1/otasicap/data/t bs_sccorder_01.dbf 7838 10 /data/ota/db2/otasicap/data/idx_sccorder_01.dbf 11479 9 /data/ota/db1/otasicap/data/tbs_sccorder_02.dbf 19028 2 /data/ota/db1/otasica p/data/rbs01.dbf 47124 18 /data/ota/db2/otasicap/data/rbs02.dbf 171997 6 /data/o ta/db1/otasicap/data/data01.dbf this shows the file/s with the most waits (at th e bottom of the list)

so by combining the two sets of information we know what block type/s in which f ile/s are causing waits. the segments in each file can be seen using a query lik e: select distinct owner, segment_name, segment_type from dba_extents where file _id = &file#; for file-nr 6: select distinct owner "owner", substr(segment_name, 1,30) "segment-name", substr(segment_type,1,20) "segment-type" from dba_extents where file_id = 6; owner -----------------------------dispatcher dispatcher disp atcher dispatcher dispatcher dispatcher dispatcher orastat sysadm sysadm sysadm sysadm sysadm sysadm sysadm segment-name -----------------------------archivio_s sc_sms_ccbs idx_msisdn_reloadfix reloadfix sscms_mscount_5 ssc_changes ssc_sms_c cbs ssc_sms_ccbs_old segment_info bkp_99_state_sscorder sscapps ssccdr sscconf s screquest sscresponse sscsmbuf segment-type ----------------table index table ta ble table table table table table table table table table table table if there are a large number of segments of the type listed then monitoring v$ses sion_wait may help isolate which object is causing the waits. repeatedly run the following statement and collect the output. after a period of time sort the res ults to see which file & blocks are showing contention: select p1 "file", p2 "bl ock", p3 "reason" from v$session_wait where event='buffer busy waits'; file bloc k reason ---------- ---------- ---------18 79362 1012 18 67842 1016 file block r eason ---------- ---------- ---------6 10526 1016 ---------------------------------------------system wide waits for "db file sequential read" ---------------------------------------------this wait happens when a session is waiting for an io to complete. typically this indicates single block reads, although reads fro m

a disk sort area may use this wait event when reading several contiguous blocks. remember io is a normal activity so you are really interested in unnecessary or slow io activity. ==> tune sql statements ---------------------------------------------------------------system wide waits for "db file scattered read" (full table scans) ----------------------------------------------------------------thi s wait happens when a session is waiting for a multiblock io to complete. this t ypically occurs during full table scans or index fast full scans. oracle reads u p to db_file_multiblock_read_count consecutive blocks at a time and scatters the m into buffers in the buffer cache. how this is done depends on the value of use _readv. if the time spent waiting for multiblock reads is significant then we ne ed to determine which segment/s we are performing the reads against. see the "ta blespace io" and "file io" sections of the estat report to get information on wh ich tablespaces / files are servicing multiblock reads (blks_read/reads>1). it i s probably best at this stage to find which sessions are performing scans and tr ace them to see if the scans are expected or not. this statement can be used to see which sessions may be worth tracing: select substr(a.sid,1,5) "sid", substr( a.process,1,7) "process", substr(a.username,1,20) "user", total_waits, time_wait ed from v$session_event v, v$session a where v.event='db file scattered read' an d v.total_waits > 0 and a.sid = v.sid order by v.total_waits desc; sid ----109 1 11 120 75 101 85 6 82 108 115 process ------12533 10391 31320 4214116 4290951 11 165 9832 10949 52360 8781 user total_waits time_waited -------------------- ---------- ----------smh_link 136172 6401 dispatcher 30045 3390 vp_link 5792 789 vp _link 5760 371 sysadm 1582 462 sysadm 1566 522 570 840 sscsmh 179 88 vp_link 85 65 sys 14 2 use_readv can have a dramatic effect on the performance of table scans. on many platforms use_readv=false performs better than true but this should be tested. d b_file_multiblock_read_count should generally be made as large as possible. the value is usually capped by oracle and so it cannot be set too high. the 'capped' value differs between platforms and versions and usually depends on the setting s of db_block_size and use_readv.

current settings use_readv db_file_multiblock_read_count boolean false integer 3 2 ---------------------------------------------system wide waits for "enqueue" (lo cal 'lock') ---------------------------------------------a wait for an enqueue i s a wait for a local 'lock'. the count and average wait times for this wait-even t can be misleading as "enqueue" waits re-arm every few seconds. to qualify how many waits have really occurred you need the enqueue waits statistic from the st atistics section of the estat report. to determine which enqueues are causing th e most waits system-wide look at view x$ksqst select ksqsttyp "lock", ksqstget " gets", ksqstwat "waits" from x$ksqst where ksqstwat>0; lo gets waits -- ---------- ---------cf 3720 2 ci 1936 2 cu 379 1 dx 23582708 7 st 4591 20 tx 19710183 16189 tx transaction lock generally due to application or table setup issues tm dml enqueue generally due to application issues, particularly if foreign key constraints hav e not been indexed. st space management enqueue usually caused by too much space management occurring (eg: small extent sizes, lots of sorting etc..) --------------------------------system wide waits for "latch free" --------------------------------latches are like short duration locks that protect critical bits of c ode. as a latch wait is typically quite short it is possible to see a large numb er of latch waits which only account for a small percentage of time. if the time spent waiting for latches is significant then we need to determine which latche s are suffering from contention. the bstat/estat section on latches shows latch activity in the period sampled. this section of the estat report is based on vie w v$latch gives a summary of latch activity since instance startup and can give an indication of which latches are responsible

for the most time spent waiting for "latch free" thus: select from where order l atch#, substr(name,1,30) gets, misses, sleeps v$latch sleeps>0 by sleeps desc; g ets misses sleeps ------------------------------ ---------- ---------cache buffe rs chains 1619686 103490 redo allocation 1934934 8607 global tx hash mapping 335 42 4493 library cache 325559 2555 redo copy 18711 2326 enqueues 593898 1781 sess ion allocation 337507 1506 cache buffers lru chain 23440 1411 enqueue hash chain s 98115 1069 undo global data 264600 791 system commit number 210693 752 transac tion allocation 87931 461 messages 113626 315 dml lock allocation 29710 206 list of block allocation 29313 176 session idle bit 34286 155 multiblock read object s 5452 35 row cache objects 326 9 global tx free list 1956 7 modify parameter va lues 2 3 shared pool 31 3 latch wait list 219 2 parallel query stats 2 1 latch# ---------11 18 37 39 19 8 2 15 9 29 16 27 7 25 26 4 13 32 35 6 38 0 50 cache buffers chains latches individual block contention can show up as contenti on for one of these latches. each cache buffers chains latch covers a list of bu ffers in the buffer cache. --------------------------------------------system wi de waits for "log file space/switch" -------------------------------------------there are several wait events which may indicate problems with the redo buffer and redo log throughput: log buffer space log file switch (checkpoint incomplete ) log file switch (archiving needed) log file switch/archive log file switch (cl earing log file) log file switch completion switch logfile command increase the log_buffer size until there is no incremental benefit (sizes > 1mb are unlikely to add any benefit) for all other waits:

- ensure redo logs are on fast disks (not raid5) - ensure redo logs are large en ough to give a sensible gap between log switches. a 'rule-of-thumb' is to have o ne log switch every 15 to 30 minutes. - ensure the archiver process is running a nd keeping up. ------------------------------------system wide waits for "log fi le sync" ------------------------------------this wait happens when a commit (or rollback) is issued and the session has to wait for the redo entry to be flushe d to disk to guarantee that instance failure will not roll back the transaction. - where possible reduce the commit frequency. eg: commit at batch intervals and not per row. - speed up redo writing (eg: do not use raid 5, use fast disks etc ..) -------------------------------------------system wide waits for "write comp lete waits" -------------------------------------------this wait happens when a requested buffer is being written to disk we cannot use the buffer while it is b eing written. if the time spent waiting for buffers to be written is significant then note the "average write queue length" if this too is large then the the ca che aging rate is too high for the speed that dbwr is writing buffers to disk. decrease the cache aging rate - increase the throughput of dbwr *************** ******* 5). dirty queue length ********************** the average write queue le ngth gives an indication of whether the cache is being cleared of dirty blocks f ast enough or not. unless the system is very high throughput the write queue sho uld never be very large. as a general guideline if the average write queue is in double figures it is certainly worth finding where the activity is coming from. if the figure is in single digits there may still be un-necessary activity in t he cache. the 2 main ways to improve the write queue length are: eliminate any u nnecessary write io from going via the cache. improve dbwr throughput. eg: use a synchronous writes, multiple database writer processes, larger block write batch . anything above 100 indicates that the dbwr is having real problems keeping up ! select sum(decode(name,'summed dirty queue length',value)) / sum(decode(name,' write requests',value)) "average write queue length" from v$sysstat where name i n ( 'summed dirty queue length','write requests') and value > 0; average write q ueue length (should be 0)

---------------------------------------0.35044 ***************************** 6). tablespace io and file io ***************************** table_space file_name r eads blks_read tablespace name file name in this tablespace number of read calls to the os number of blocks read. the above two differ only when multi-block rea ds are being performed. eg: on full table scans we read up to db_file_multiblock _read_count blocks per read. total time for the reads in 1/100ths of a second nu mber of os write calls number of blocks written write time in 1/100ths of a seco nd. nb: this figure may be incorrect. read_time writes blks_wrt write_time table_space reads blks_read read_time writes blks_wrt write_time megabytes ---------------- ------- ---------- ---------- ---------- ---------- -----------------data 24487 88794 4713 17011 17011 531654 524 idx 6844 6844 26326 38219 38219 1454912 524 rbs 2 2 2 102702 102702 5333108 1598 system 101 152 71 97 97 3542 10 5 tbs_sccorder 684066 6344009 86376 46697 46697 2081706 3222 tbs_sccorder_idx 12 5173 125174 847903 228494 228494 12198710 3222 tbs_sscms 28801 28801 41554 39439 39439 1235851 2148 tbs_sscms_idx 20732 20732 5126 231 231 6541 2148 temp 51 725 27 89 678 242 1049 tools 0 0 0 0 0 0 105 users 0 0 0 15 15 410 105 read-time pe r block in [ms] = ((read_time/100) / blks_read) * 1000 tbs_sccorder: tbs_sccorde r_idx: tbs_sscms: tbs_sscms_idx: ((86'376/100)/6'344'009)*1000 = 0.13 ((847'903/ 100)/125'174)*1000 = 67.73 ((41'554/100)/28'801)*1000 = 14.43 ((5'126/100)/)20'7 32*1000 = 2.47 ms ms ms ms (very fast) (very slow) (ok) (very fast) table_space file_name reads blks_read read_time writes blks_wrt write_time megab ytes ----------------- ------------------------------------------------ ---------

---------- ---------- ---------- ---------- ---------- ---------data /data/ota/d b1/otasicap/data/data01.dbf 88794 4713 17011 17011 531654 524 idx /data/ota/db2/ otasicap/data/idx_01.dbf 6844 26326 38219 38219 1454912 524 rbs /data/ota/db1/ot asicap/data/rbs01.dbf 1 0 23922 23922 854404 524 rbs /data/ota/db2/otasicap/data /rbs02.dbf 1 2 78780 78780 4478704 1074 system /data/ota/db1/otasicap/data/syste m01.dbf 152 71 97 97 3542 105 tbs_sccorder /data/ota/db1/otasicap/data/tbs_sccor der_01.dbf 2841155 34210 24178 24178 806926 1074 tbs_sccorder /data/ota/db1/otas icap/data/tbs_sccorder_02.dbf 2075092 41336 22519 22519 1274780 1074 tbs_sccorde r /data/ota/db1/otasicap/data/tbs_sccorder_03.dbf 1427762 10830 0 0 0 1074 tbs_s ccorder_idx /data/ota/db2/otasicap/data/idx_sccorder_01.dbf 23354 49920 52053 52 053 1963087 1074 tbs_sccorder_idx /data/ota/db2/otasicap/data/idx_sccorder_02.db f 84368 743566 124286 124286 8090752 1074 tbs_sccorder_idx /data/ota/db2/otasica p/data/idx_sccorder_03.dbf 17452 54417 52155 52155 2144871 1074 tbs_sscms /data/ ota/db1/otasicap/data/tbs_sccms_01.dbf 12889 19041 17960 17960 562416 1074 tbs_s scms /data/ota/db1/otasicap/data/tbs_sccms_02.dbf 15912 22513 21479 21479 673435 1074 tbs_sscms_idx /data/ota/db2/otasicap/data/idx_sccms_01.dbf 20428 4738 184 184 4997 1074 tbs_sscms_idx /data/ota/db2/otasicap/data/idx_sccms_02.dbf 304 388 47 47 1544 1074 temp /data/ota/db1/otasicap/data/temp01.dbf 725 27 89 678 242 1 049 tools /data/ota/db1/otasicap/data/tools.dbf 0 0 0 0 0 105 users /data/ota/db 1/otasicap/data/users.dbf 0 0 15 15 410 105 ********************** 7). fragmente d objects ********************** set feed off set pagesize 5000 break on owner s kip 1 on tablespace_name on segment_type column datum new_value datum noprint co lumn owner format a10 heading 'owner' column tablespace_name format a20 heading 'tablespace' column segment_type format a10 heading 'segment-|type' column segme nt_name format a30 heading 'segment-|name' column extent_id format 999 heading ' number of|extents' column bytes format 999,999,999,999 heading 'size|[bytes]' -- looking for frgmented objects -select to_char(sysdate, 'mm/dd/yy') datum, owne r, tablespace_name, 24487 6844 1 1 101 242174 282835 159057 23354 84367 17452 12889 15912 20428 304 51 0 0

segment_type, segment_name, count(extent_id) extent_id, sum(bytes) bytes from sy s.dba_extents where substr(owner,1,10) not in ('sys') group by owner, tablespace _name, segment_type, segment_name having count(extent_id) > 3 order by 1,2,3,4; owner tablespace extents [bytes] ---------- ---------------------------- --------------dispatcher idx 4 20,971,520 tbs_sccorder 4 419,430,400 tbs_sccorder_idx 4 419,430,400 sysadm tbs_sscms 4 2,076,172,288 type name ---------- -----------------------------index table index table pk_ssc_sms_ccbs sscorder idx_sscorder_history_msisdn sscms ************************************************* 8). sessions with bad buffer c ache hit ratio in % ************************************************* set feed o ff; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'show sessions with bad buffer cac he hit ratio in %' skip 2 -select substr(a.username,1,12) "user", a.sid "sid", b .consistent_gets "consgets", b.block_gets "blockgets", b.physical_reads "physrea ds", 100 * round((b.consistent_gets + b.block_gets - b.physical_reads) / (b.cons istent_gets + b.block_gets),3) hitratio from v$session a, v$sess_io b where a.si d = b.sid and (b.consistent_gets + b.block_gets) > 0 and a.username is not null order by hitratio asc; show sessions with bad buffer cache hit ratio in %

user sid consgets blockgets physreads hitratio ------------ ---------- --------- ---------- ---------- ---------sysadm 101 45719 6 38640 15.5 dispatcher 111 46 6434 16 390966 16.2 vp_link 95 94058 6 65802 30 vp_link 75 94150 4 43350 54 disp atcher 84 1288381 28 470437 63.5 vp_link 40 436526 2 116192 73.4 vp_link 90 4375 87 2 112440 74.3 smh_link 109 1920356 1345626 799163 75.5 sscsmsci 68 5 0 1 80 d ispatcher 94 52 8 9 85 sys 115 58443 6811 6845 89.5 vp_link 88 19 2 2 90.5 vp_li nk 72 374313 998401 78614 94.3 vp_link 89 373818 997023 78529 94.3 vp_link 87 37 3435 995770 78406 94.3 vp_link 97 373546 996162 78587 94.3 vp_link 93 374399 998 969 78478 94.3 vp_link 80 7048 18880 1444 94.4 vp_link 70 1813 4768 364 94.5 vp_ link 92 1851 4952 369 94.6 vp_link 86 1870 4994 362 94.7 mig_ota 91 1113 8 46 95 .9 vp_link 104 21 14 1 97.1 vp_link 98 56 2 1 98.3 vp_link 96 239 578 13 98.4 di spatcher 110 1092370 3875255 59535 98.8 sscsmh 105 59195 35151 1035 98.9 tmh_lin k 77 842 2086 30 99 vp_link 114 387838 853135 11724 99.1 sscsmh 37 984588 543820 11500 99.2 sscsmh 54 2318348 1304849 20178 99.4 sscfsm 52 2938795 2408492 25907 99.5 sscfsm 53 2933194 2403007 25963 99.5 sscsmh 71 2835536 1592916 23697 99.5 sscfsm 69 2938692 2407723 26245 99.5 sscfsm 60 2934409 2404253 25990 99.5 sscfsm 59 2936309 2406120 25942 99.5 sscdsp 103 18518943 10226773 106777 99.6 dispatch er 51 1200555 2587257 12744 99.7 -############################################## #################################### ########### --- %purpose: how to implement "sleep function" with pl/sql ? --the next example trytogetslot tries to get free -system resources (e.g. to create an index on a -busy table). the function wait s for some seconds -and then tries to get the resource again. after -a counter h ave reached the maximum, the routine -exits. --################################# ################################################# ###########

-create or replace procedure trytogetslot is gotit boolean := false; count numbe r := 0; begin while (not gotit and not (count > 10)) loop begin -- try to get fr ee slot, if ok, set gotit = true -- else exception will automatically fire. (ins ert code here) gotit := true; exception when others then gotit := false; dbms_lo ck.sleep(10); count := count + 1; end; end loop; end; / -####################### ########################################################### ########### --- %pur pose: how to query a n x m relation using the union construct to avoid the ora-1 417 error --- consider the following situation: we have employees and projects. --- an employee can be registered (work for) in 0, 1or more projects. for a cert ain project, -- 0 one or more employees are allocated. we have a typical many-to -many relationship which -- is normalized with the intersection entity projalloc . --############################################################################ ###### ########### -create table employee ( emp_id number not null, name varchar 2(30), constraint emp_pk primary key (emp_id) ); create table project ( proj_id number not null, name varchar2(30), constraint proj_pk primary key (proj_id) ); create table projalloc ( emp_id number not null, proj_id number not null, constr aint pa_pk primary key (proj_id, emp_id), constraint pa_fk1 foreign key (proj_id ) references project (proj_id), constraint pa_fk2 foreign key (emp_id) reference s employee (emp_id) );

insert insert insert insert insert insert insert insert insert insert into into into into into into into into into into employee employee employee employee employee project project project project pro ject (emp_id,name) (emp_id,name) (emp_id,name) (emp_id,name) (emp_id,name) (proj_id,n ame) (proj_id,name) (proj_id,name) (proj_id,name) (proj_id,name) values values values values values values values values values values (1,'allen'); (2,'baker'); (3,'ford'); (4,'miller'); (5,'scott'); (1,'project (2, 'project (3,'project (4,'project (5,'project (1,1); (1,2); (1,3); (2,2); (2,5); (3,3); (4,3); 01'); 02'); 03'); 04'); 05'); insert into insert into insert into insert into insert into insert into insert i nto commit; projalloc projalloc projalloc projalloc projalloc projalloc projalloc (proj_id,emp_id) (proj_id,emp_id) (proj_id,emp_id) (proj_id,emp_id) (proj_id,emp _id) (proj_id,emp_id) (proj_id,emp_id) values values values values values values values select e.name employee,p.name name from employee e, projalloc pa, project p wher e e.emp_id = pa.emp_id(+) and p.proj_id = pa.proj_id(+) order by 1 ora-01417: a table may be outer joined to at most one other table --- solution --- use the un ion construct to query the two special cases -- (all employees with no project a ssigned and -- all projects with no employees assigned). -select e.name employee ,p.name project from employee e, projalloc pa, project p where e.emp_id = pa.emp _id and p.proj_id = pa.proj_id union select e.name, null from employee e, projal loc pa where e.emp_id = pa.emp_id(+) and pa.emp_id is null union select null, p. name project from project p, projalloc pa where p.proj_id = pa.proj_id(+) and pa .proj_id is null order by 1; employee -----------------------------allen baker b aker project ----------project 01 project 01 project 02

ford ford ford miller scott project 01 project 03 project 04 project 02 project 05 -############################################################################### ### ########### --- %purpose: how to reclaim unused_space from indexes and table s using dbms_space.unused_space --- before growing a datafile in a tablespace th at shows on your -- space analysis reports, search for space that can be reclaim ed -- from an object that was poorly sized initially. tables and indexes -- can be altered with a deallocate unused, thus reclaiming unused -- space above the h igh-water mark. --- example: alter table emp deallocate unused; --- this script prompts you for two pieces of information: --- 1. the type of segment to retriev e, (i=indexes, t=tables) --- 2. the tablespace_name to retrieve from. --- simply put, this allows you to retrieve one of these segment -- types by tablespace_na me. it is important to note that deallocating -- unused space became available w ith oracle version 7.3. --###################################################### ############################ ###########--accept type prompt "enter the type of segment to check (i=index, t=table): " accept ts_name prompt "enter the tablespa ce name that you wish to check: " set serveroutput on feedback off -spool unused _space.lst -declare v_total_blocks number; v_total_bytes number; v_unused_blocks number; v_unused_bytes number; v_file_id number; v_block_id number; v_last_bloc k number; v_used number; v_owner varchar2(12); v_segment varchar2(80); v_type ch ar(1); cursor index_c is select owner, index_name from sys.dba_indexes

where tablespace_name = upper('&ts_name'); cursor select from where table_c is o wner, table_name sys.dba_tables tablespace_name = upper('&ts_name'); begin dbms_output.enable(100000); v_type := '&type'; if (v_type = 'i' or v_type = 'i') then open index_c; fetch index_c into v_owner, v_segment; while index_c%f ound loop -dbms_space.unused_space(v_owner, v_segment, 'index', v_total_blocks, v_total_bytes, v_unused_blocks, v_unused_bytes, v_file_id, v_block_id, v_last_bl ock); -dbms_output.put_line(chr(10)); dbms_output.put_line('index name = '||v_se gment); dbms_output.put_line('total blocks = '|| v_total_blocks); dbms_output.pu t_line('total bytes = '||v_total_bytes); dbms_output.put_line('unused blocks = ' || v_unused_blocks); dbms_output.put_line('unused bytes = '|| v_unused_bytes); v _used := v_total_blocks - v_unused_blocks; dbms_output.put_line('used blocks = ' ||v_used); v_used := v_total_bytes - v_unused_bytes; dbms_output.put_line('used bytes = '||v_used); dbms_output.put_line('last used extents file id = '||v_file_ id); dbms_output.put_line('last used extents block id = '||v_block_id); dbms_out put.put_line('last used block = '||v_last_block); fetch index_c into v_owner, v_ segment; end loop; close index_c; elsif (v_type = 't' or v_type = 't') then open table_c; fetch table_c into v_owner, v_segment; while table_c%found loop -dbms_ space.unused_space(v_owner, v_segment, 'table', v_total_blocks, v_total_bytes, v _unused_blocks, v_unused_bytes, v_file_id, v_block_id, v_last_block); -v_used := v_total_bytes - v_unused_bytes; dbms_output.put_line(chr(10)); dbms_output.put_ line('table name = '||v_segment); dbms_output.put_line('total blocks = '|| v_tot al_blocks); dbms_output.put_line('total bytes = '|| v_total_bytes); dbms_output. put_line('unused blocks = '|| v_unused_blocks);

dbms_output.put_line('unused bytes = '|| v_unused_bytes); v_used := v_total_bloc ks - v_unused_blocks; dbms_output.put_line('used blocks = '||v_used); v_used := v_total_bytes - v_unused_bytes; dbms_output.put_line('used bytes = '||v_used); d bms_output.put_line('. kbytes = '||v_used/1024); dbms_output.put_line('. mbytes = '|| (v_used/1024)/1024); dbms_output.put_line('last used extents file id = '|| v_file_id); dbms_output.put_line('last used extents block id = '||v_block_id); d bms_output.put_line('last used block = '||v_last_block); fetch table_c into v_ow ner, v_segment; end loop; close table_c; end if; end; / spool off -############# ##################################################################### ########## # --- %purpose: install sql*plus and pl/sql help tables in data dictionary for: sql>help command --- use: privileges for system user --######################### ######################################################### ########### -#!/bin/sh $oracle_home/bin/svrmgrl << eof connect system/manager @$oracle_home/sqlplus/ad min/help/helptbl.sql; exit; eof $oracle_home/bin/svrmgrl << eof connect system/m anager @$oracle_home/sqlplus/admin/help/helpindx.sql; exit; eof $oracle_home/bin /sqlldr userid=system/manager control=$oracle_home/sqlplus/admin/help/plushelp.c tl $oracle_home/bin/sqlldr userid=system/manager control=$oracle_home/sqlplus/ad min/help/plshelp.ctl $oracle_home/bin/sqlldr userid=system/manager control=$orac le_home/sqlplus/admin/help/sqlhelp.ctl -######################################## ########################################## ########### --- %purpose: monitor dat a access activities (full table and index scans, chained rows)

--- use: needs oracle dba access --############################################# ##################################### ########### -set feed off; set pagesize 10 000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; se t verify off; set termout on; column column column column column column colum tt itle spool select from where or or ttitle select statistic# na ria rts ra pcr cl left form form form form form form form 999 a32 990.90 990.90 9999999990 990.90 990.90 head head head head head head head 'id' 'statistic' 'row access via|inde x [%]' 'row access via|table scan [%]' 'rows accessed' 'chained|rows [%]' 'clust er|length' skip 2 'monitor data access activities' monitor_data_activites.log rpad (name, 32, '.') as na, value v$sysstat name like '%table scan%' name like '%table fetch%' name like '%cluster%'; off a.value + b .value as a.value / (a.value + b.value) * 100.0 as b.value / (a.value + b.value) * 100.0 as c.value / (a.value + b.value) * 100.0 as e.value / d.value as v$syss tat a, v$sysstat b, v$sysstat c, v$sysstat d, v$sysstat e a.name = 'table fetch by rowid' b.name = 'table scan rows gotten' c.name = 'table fetch continued row' d.name = 'cluster key scans' e.name = 'cluster key scan block gets' ra, ria, rt s, pcr, cl from where and and and and / -############################################################################# ##### ########### --

-- %purpose: monitor private sql areas and pl/sql space in the uga and sga --pl/ sql allocates most memory from the uga which is -located in the sga when shared servers are used --uga = user global area -sga = system global area --- use: nee ds oracle dba access --######################################################### ######################### ########### -set feed off; set pagesize 10000; set wra p off; set linesize 200; set heading on; set tab on; set scan on; set verify off ; set termout on; column column column column column column ttitle spool select na nr_sess c1 c2 c3 c4 left head head head head head head 'statistic' '#users' ' sum|[kbyte]' 'avg|[kbyte]' 'min|[kbyte]' 'max|[kbyte]' format format format form at format format a29 9999 999990.90 999990.90 999990.90 999990.90 skip 2 'monitor private sql areas and pl/sql space' monitor_private_sql_areas.log rpad (b.name, 29, '.') as na, count(*) as nr_sess, sum(a.value)/1024.0 as c1, avg(a.value)/1024.0 as c2, min(a.value)/1024.0 as c3 , max(a.value)/1024.0 as c4 v$sesstat a, v$statname b a.statistic# = b.statistic # (b.name like '%pga%' b.name like '%uga%' b.name like '%stored%') by b.name from where and or or group / -############################################################################# ##### ########### --- %purpose: monitor sql*net communication activities --- use : needs oracle dba access ---

################################################################################ ## ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200 ; set heading on; set tab on; set scan on; set verify off; set termout on; colum n column na value format a39 format 99999999990 heading 'statistic' heading 'val ue' spool monitor_sqlnet_activities.log select from where order / spool off; -###### ############################################################################ ### ######## --- %purpose: monitor sort activities (sorts in memory, sorts on disk) --- use: needs oracle dba access --############################################# ##################################### ########### -set feed off; set pagesize 10 000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; se t verify off; set termout on; column column column column column ttitle spool st atistic# na name va value left format format format format format 999 heading a3 2 heading a32 heading a8 heading 9999999990 'id' 'parameter' 'statistik' 'value' rpad (name, 39, '.') as na, value v$sysstat name like ('%sql*net%') by na 'monitor sort activities' skip 2 monitor_sort_activities.log

select from where / rpad (name, 32, '.') as na, value as va v$parameter name like '%sort%' ttitle off select name, value from v$sysstat where name in ('sorts (rows)', 'sor ts (memory)', 'sorts (disk)') / spool off; -#################################### ############################################## ########### --- %purpose: nls: sh ow current nls database settings from sys.props$ --############################# ##################################################### ########### -spool show_nl s_current_settings.lst ttitle left 'show current nls database settings' skip 2 s et feed off set pagesize 30000 set linesize 200 column name format a25 column va lue$ format a35 select name,value$ from sys.props$; spool off; -################ ################################################################## ########### -- %purpose: nls: show valid nls parameters (territory, characterset) from v$nls _valid_values --################################################################ ################## ########### -spool show_nls_valid_values.lst ttitle left 'sho w valid nls parameters (territory, characterset)' skip 2 set feed off set pagesi ze 30000 set linesize 200 column parameter format a15 column value format a15

select parameter,value from v$nls_valid_values where parameter = 'characterset' order by value; spool off; -#################################################### ############################## ########### --- %purpose: overview (owner, object _name, object_type) of all invalid objects --- use: needs oracle dba access --## ################################################################################ ########### -spool show_invalid_objects_summary.lst set pause off set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; ttitle left 'overview of invalid objects' skip 2 c olumn column column column object_type format a25 wrap heading 'object|type' obj ect_name format a25 wrap heading 'object|name' status format a8 heading 'status' owner format a10 wrap heading 'owner' select owner, object_name, object_type, status from dba_objects where status != 'valid'; spool off; -########################################################### ####################### ########### --- %purpose: performance enhancements with pl/sql dbms_sql bulk-operations instead of looping --- use: needs oracle dba acc ess --########################################################################## ######## ########### -declare vcursor integer := dbms_sql.open_cursor; vcount in teger;

vstatement varchar2(2000); vemps dbms_sql.varchar2_table; begin vstatement := 'u pdate emp set sal = sal + 1' || ' where ename = :thisename'; vemps(1) := 'king'; vemps(2) := 'miller'; vemps(3) := 'huber'; vemps(4) := 'scott'; vemps(5) := 'ad ams'; begin dbms_sql.parse(vcursor,vstatement, dbms_sql.native); dbms_sql.bind_a rray(vcursor,'thisename',vemps); vcount := dbms_sql.execute(vcursor); dbms_sql.c lose_cursor(vcursor); dbms_output.put_line('vcount = ' || to_char(vcount)); end; end; -######################################################################### ######### ########### --- %purpose: recompile all invalid db-objetcs with depend ency tracking (very handy script) --- environment: execute under db-user system or sys --####################################################################### ########### ########### -set heading off; set feed off; set pagesize 10000; set wrap off; set linesize 200; set tab on; set scan off; set verify off; -spool gen _inv_obj.sql; select decode (object_type, 'package body', 'alter package ' || a. owner||'.'||object_name || ' compile body;', 'alter ' || object_type || ' ' || a .owner||'.'||object_name || ' compile;') from dba_objects a, (select max(level) order_number, object_id from public_dependency connect by object_id = prior refe renced_object_id group by object_id) b where a.object_id = b.object_id(+) and st atus = 'invalid' and object_type in ('package body', 'package', 'function', 'pro cedure','trigger', 'view') order by order_number desc,object_type,object_name; s pool off;

@gen_inv_obj.sql; spool comp_all.tmp select decode (object_type, 'package body', 'alter package ' || owner ||'.'||object_name || ' compile body;', 'alter ' || object_type || ' ' || owner||'.'||object_name || ' compile;' ) from dba_objects a, sys.order_object _by_dependency b where a.object_id = b.object_id (+) and a.status = 'invalid' an d a.object_type in ('package body','package','function','procedure','trigger','v iew') order by b.dlevel desc, a.object_type, a.object_name; -spool off; set head ing on; set feed on; set scan on; set verify on; -@comp_all.tmp -############### ################################################################### ########### --- %purpose: sql statement to create the plan_table used by explain plan --#### ############################################################################## # ########## -create table plan_table ( statement_id varchar2(30), timestamp date, remarks varchar2(80), operation varchar2(30), options varchar2(30), object_node varchar2(128), object_owner varchar2(30), object_name varchar2(30), object_inst ance numeric,

object_type varchar2(30), optimizer varchar2(255), search_columns numeric, id nu meric, parent_id numeric, position numeric, cost numeric, cardinality numeric, b ytes numeric, other_tag varchar2(255), other long); -########################### ####################################################### ########### --- %purpose : script to increase a sequence above the value the related attribute has --#### ############################################################################## # ########## --- akadia sql utils --- can be used after data migrations --- paramt ers: -1: sequence name -2: table name -3: attribute name --- sample usage: -@inc seq.sql my_sequence my_table my_attribute --------------------------------------------------------------------------------set serveroutput on size 1000000; -de clare dummy number := 0; curr number := 0; begin -select &1..nextval into dummy from dual; dbms_output.put('start with next value=' || dummy); -select max(&3) i nto curr from &2; while dummy < curr loop select &1..nextval into dummy from dua l; end loop; -dbms_output.put_line(', end=' || dummy); -end; / -################ ################################################################## ###########

--- %purpose: send e-mail messages from pl/sql with oracle 8.1.6 using utl_tcp o r utl_smtp --- notes: from oracle8i release 8.1.6 one can send e-mail messages directly from pl/sql using either the utl_tcp or utl_smtp -packages. no pipes or external procedures required. --the utl_tcp is a tpc/ip package that provides p l/sql procedures -to support simple tcp/ip-based communications between servers and the -outside world. it is used by the smtp package, to implement oracle serv er-based -clients for the internet email protocol. --this package requires that you install the jserver option --- author: frank naude (frank@ibi.co.za) --##### ############################################################################# ## ######### -create or replace procedure send_mail ( msg_from varchar2 := 'martin. zahn@akadia.com', -- must be a vaild e-mail address ! msg_to varchar2 := 'martin .zahn@akadia.com', -- must be a vaild e-mail address ! msg_subject varchar2 := ' message from pl/sql daemon', msg_text varchar2 := 'this message was automaticall y send by pl/sql daemon' ) is conn utl_tcp.connection; rc integer; mailhost varc har2(30) := 'rabbit.akadia.com'; begin conn := utl_tcp.open_connection(mailhost, 25); -- open the smtp port dbms_output.put_line(utl_tcp.get_line(conn, true)); r c := utl_tcp.write_line(conn, 'helo '||mailhost); dbms_output.put_line(utl_tcp.g et_line(conn, true)); rc := utl_tcp.write_line(conn, 'mail from: '||msg_from); d bms_output.put_line(utl_tcp.get_line(conn, true)); rc := utl_tcp.write_line(conn , 'rcpt to: '||msg_to); dbms_output.put_line(utl_tcp.get_line(conn, true)); rc : = utl_tcp.write_line(conn, 'data'); -- start message body dbms_output.put_line(u tl_tcp.get_line(conn, true)); rc := utl_tcp.write_line(conn, 'subject: '||msg_su bject); rc := utl_tcp.write_line(conn, ''); rc := utl_tcp.write_line(conn, msg_t ext); rc := utl_tcp.write_line(conn, '.'); -- end of message body with a "." dbm s_output.put_line(utl_tcp.get_line(conn, true)); rc := utl_tcp.write_line(conn, 'quit'); dbms_output.put_line(utl_tcp.get_line(conn, true)); utl_tcp.close_conne ction(conn); -- close the connection exception when others then raise_applicatio n_error(-20000, 'unable to send e-mail message from pl/sql procedure'); end;

/ show errors -- examples: set serveroutput on exec send_mail(); exec send_mail( msg_to =>'martin.zahn@akadia.com'); exec send_mail(msg_to =>'martin.zahn@akadia. com', msg_text=>'how to send e-mail from pl/sql'); create or replace procedure s end_mail2 ( sender in varchar2, recipient in varchar2, message in varchar2) is m ailhost varchar2(30) := 'rabbit.akadia.com'; smtp_error exception; mail_conn utl _tcp.connection; procedure smtp_command(command in varchar2, ok in varchar2 defa ult '250') is response varchar2(3); rc integer; begin rc := utl_tcp.write_line(m ail_conn, command); response := substr(utl_tcp.get_line(mail_conn), 1, 3); if (r esponse <> ok) then raise smtp_error; end if; end; begin mail_conn := utl_tcp.op en_connection(mailhost, 25); smtp_command('helo ' || mailhost); smtp_command('ma il from: ' || sender); smtp_command('rcpt to: ' || recipient); smtp_command('dat a', '354'); smtp_command(message); smtp_command('quit', '221'); utl_tcp.close_co nnection(mail_conn); exception when others then raise_application_error(-20000, 'unable to send e-mail message from pl/sql'); end; / exec send_mail2('martin.zah n@akadia.com','martin.zahn@akadia.com','test'); create or replace procedure send _mail3 (sender in varchar2, recipient in varchar2, message in varchar2) is mailh ost varchar2(30) := 'rabbit.akadia.com'; mail_conn utl_smtp.connection;

begin mail_conn := utl_smtp.open_connection(mailhost, 25); utl_smtp.helo(mail_co nn, mailhost); utl_smtp.mail(mail_conn, sender); utl_smtp.rcpt(mail_conn, recipi ent); utl_smtp.data(mail_conn, message); utl_smtp.quit(mail_conn); exception whe n others then raise_application_error(-20000, 'unable to send e-mail message fro m pl/sql'); end; / exec send_mail3('martin.zahn@akadia.com','martin.zahn@akadia. com','subject: test'); -######################################################## ########################## ########### --- %purpose: set private synonyms to sch ema of a connected oracle user --- use: each oracle user --##################### ############################################################# ########### -set t ermout on; set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading off; set tab on; set scan on; set verify off; -prompt prompt **** priva te synonyme auf waehlbares schema setzen ***** prompt prompt sie brauchen schrei brechte im aktuellen verzeichnis, prompt damit das sql-script gen_private_syn.sq l generiert prompt werden kann. dieses wird (leider) nach der ausfuehrung prompt nicht automatisch geloescht, da sqlplus leider nicht prompt weiss wie man das m acht ... prompt prompt ******************************************************** prompt whenever sqlerror exit sql.code accept schema_name char prompt 'enter sch ema (object owner): ' --- generate and run file with synonym commands in current directory -set termout off; spool gen_private_syn.sql; select 'drop synonym '|| synonym_name||';' from user_synonyms;

-select 'create synonym '||table_name||' for &&schema_name'||'.'||table_name ||' ;' from all_tables where (upper(owner) like upper('%&&schema_name%') or upper(ow ner) like upper('&&schema_name')); -select 'create synonym '||sequence_name||' f or &&schema_name'||'.'||sequence_name ||';' from all_sequences where (upper(sequ ence_owner) like upper('%&&schema_name%') or upper(sequence_owner) like upper('& &schema_name')); -select distinct 'create synonym '||name||' for &&schema_name'| |'.'||name||';' from all_source where (upper(owner) like upper('%&&schema_name%' ) or upper(owner) like upper('&&schema_name')) and upper(type) in ('procedure',' function','package'); spool off; set feed on; set termout on; @gen_private_syn.s ql; exit; -##################################################################### ############# ########### --- %purpose: show 'who owns what where' in the databa se --########################################################################### ####### ########### --- script to map tablespace names to database -- owners, an d database owners to tablespaces. -- this will allow you to see who owns what wh ere. -- in the event of a tablespace loss, you would -- then be able to quickly determine what users -- and tablespaces will be affected. so you should -- start this script from every export and save -- the output files at the same place as the -- export file. --######################################################### ######################### ########### set set set set set set set set set feed o ff; pagesize 10000; wrap off; linesize 200; heading on; tab on; echo off; scan o n; verify off; left 'output generated by: ' sql.user ttitle skip -

skip left 'who owns what where' skip left 'oracle version ' format a15 sql.relea se skip 2 set feed off set pagesize 10000 break on owner on tablespace_name colu mn owner format a20 heading 'owner' column tablespace_name format a32 heading 't ablespace' column objects format a26 heading 'objects' spool who_owns_what_where .lst; select substr(owner,1,20) owner, substr(tablespace_name,1,32) tablespace_n ame, count(*) || ' tables' objects from sys.dba_tables group by substr(owner,1,2 0), substr(tablespace_name,1,32) union select substr(owner,1,20) owner, substr(t ablespace_name,1,32) tablespace_name, count(*) || ' indexes' objects from sys.db a_indexes group by substr(owner,1,20), substr(tablespace_name,1,32); clear colum ns clear breaks column tablespace_name format a32 heading 'tablespace' column ow ner format a20 heading 'owner' column objects format a26 heading 'objects' break on tablespace_name on owner select substr(tablespace_name,1,32) tablespace_name , substr(owner,1,20) owner, count(*) || ' tables' objects from sys.dba_tables gr oup by substr(tablespace_name,1,32), substr(owner,1,20) union select substr(tabl espace_name,1,32) tablespace_name, substr(owner,1,20) owner, count(*) || ' index es' objects from sys.dba_indexes group by substr(tablespace_name,1,32), substr(o wner,1,20); spool off; -######################################################## ########################## ########### --- %purpose: show 'who uses what objects ' in the database

--############################################################################## #### ########### --- das diagramm table access zeigt alle datenbankobjekte, welche zur -- zeit von welcher session benutzt werden. --############################# ##################################################### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'who uses what objects' skip 2 select sid "sid", substr(owner,1,15) "owner", substr(object,1,20) "object" from v$acce ss where owner != 'sys' order by owner; -####################################### ########################################### ########### --- %purpose: show buffe r cache hit ratio in % for active instance since last startup --################ ################################################################## ########### -- der buffer cache enth lt kopien der gelesenen daten blocks aus -- den datenbank files. alle sessions teilen sich den buffer cache, der inhalt -- des buffer cach es wird gem ss einem lru algorithmus mittels dbwr auf die -- db geschrieben. muss ein block im datenbankfile gelesen werden, so handelt -- es sich dabei um einen cache miss, wird der block bereits im memory gefunden -- so spricht man von eine m cache hit. -- die tabelle v$sysstat zeigt die kumulierten werte seit die insta nce -- gestartet wurde. die physical reads seit dem instance startup verschlecht ert -- die hit-ratio, nach einer bestimmten zeit pendelt sich der wert ein. --es sollte ein hitratio mit folgenden werten angestrebt werden: --- datenbank mit vielen online-transaction intensiven benutzern: 98% -- batch intensive applikat ion: 89% --##################################################################### ############# ###########

-set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading o n; set tab on; set scan on; set verify off; -ttitle left 'show buffer cache hit ratio in %' skip 2 -select (1 - (sum(decode(a.name,'physical reads',value,0)) / (sum(decode(a.name,'consistent gets',value,0)) + sum(decode(a.name,'db block get s',value,0))))) * 100 "hit ratio in %" from v$sysstat a; -###################### ############################################################ ########### --- %pu rpose: show characteristics for system and other rollback segments --########### ####################################################################### ######## ### -spool show_rollback_segment.lst ttitle left 'rollback-segment status' skip 2 set feed off set pagesize 10000 column datum new_value datum noprint column ta blespace_name format a32 heading 'tablespace' column segment_name format a16 hea ding "rollback-segment" column status format a15 heading "status" column owner f ormat a10 heading "owner" select to_char(sysdate, 'mm/dd/yy') datum, segment_nam e, tablespace_name, status, owner from sys.dba_rollback_segs; ttitle off; select from where and 'number of extents in system rollback segment (1): ' || count(*) "extents" dba_extents segment_name = 'system' segment_type = 'rollback'; select 'number of extents in system rollback segment (2): ' || extents "extents" from v$rollstat where usn = 0; select 'maximal number of extents in system roll back segment: ' || max_extents "max extents" from dba_rollback_segs

where segment_name = 'system'; ttitle skip 2 left 'system rollback-segment statu s' select usn ,extents,rssize,hwmsize,optsize from v$rollstat where usn = 0; spool off; -----usn rollback segment number (0 = system rs) extents number of allocate d extents. rssize total size of the rollback segment in bytes. hwmsize high wate r mark of rollback segment in bytes optsize optimal size of rollback segment (sh ould be null). -############################################################################### ### ########### --- %purpose: show constraints of tabelles for a schema owner wh ich be choosen --- use: needs oracle dba access --############################## #################################################### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -spool show_constraints.lst ttitle off; column owne r format a8 heading 'table|owner' column constraint_name format a30 heading 'con straint|name' column search_condition format a30 heading 'text' column table_nam e noprint new_value tab column column_name format a15 heading 'column|name' colu mn r_constraint_name format a30 heading 'reference|constraint' column status for mat a8 heading 'status' ttitle left 'constraints of tabelle: 'tab skip 2 accept user_namen char prompt 'schema owner: ' break on table_name skip page on owner s kip 2 on constraint_name skip select c.constraint_name, i.search_condition,

c.table_name, c.column_name, i.r_constraint_name, i.status from dba_cons_columns c, dba_constraints i where i.table_name = c.table_name and i.constraint_name = c.constraint_name and i.owner = c.owner and i.owner like upper('&user_namen') or der by c.table_name, c.constraint_name, c.column_name; spool off; -############# ##################################################################### ########## # --- %purpose: show contents of the controlfile and oracle data dictionary --use: needs oracle dba access --################################################# ################################# ########### -ttitle left 'output generated by: ' sql.user ' at: ' format a8 datum left 'oracle version ' format a15 sql.releas e skip skip left 'datafiles in data dictionary (view: dba_data_files)' skip 2 se t feed off set pagesize 10000 break on tablespace_name column datum new_value da tum noprint column tablespace_name format a10 heading "tablespace" column file_n ame format a38 heading "datafile" column file_id format 99 heading "file-id" col umn bytes format 99,999,999 heading "space|[kb]" column status format a9 heading "status" select to_char(sysdate, 'mm/dd/yy') datum, tablespace_name, file_name, file_id, bytes/1000 bytes, status from dba_data_files order by file_id; ttitle left 'datafiles in controlfile (table: v$dbfile)' skip 2 set feed off set pagesi ze 10000

column name format a40 heading "datafile" column file# format 99 heading "file-i d" select name,file# from v$dbfile; ttitle left 'logfiles in controlfile (table: v$logfile)' skip 2 set feed off set pagesize 10000 column member format a40 hea ding "logfile" column group# format 99 heading "group-nr" column status format a 10 heading "status" select member,group#,status from v$logfile; -############### ################################################################### ########### --- %purpose: show db-events which causing sessions to wait --################## ################################################################ ########### --die v$session_wait view enth lt s mtliche events, welche die user-- und system sess ions in den wartezustand versetzen. diese view kann -- verwendet werden, um rasc h einen performance engpass herauszufinden. --- eine waiting time von 0 zeigt an , dass die session -- gerade auf einen event wartet. grosse wait times weisen au f ein -- performance problem hin (siehe oracle tuning guide seite a-4). --###### ############################################################################ ### ######## -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'session event s' skip 2 select w.sid "sid", nvl(substr(s.username,1,15),'background') "user", substr(w.event,1,25) "event", w.wait_time "wait time" from v$session_wait w, v$s ession s where w.sid = s.sid order by 2,4; -#################################### ############################################## ########### --- %purpose: show db -files with heavy i/o (where are hotspots of reads und writes) ?

--read_pct: prozent an gesamten reads, summe von read_pct = 100% -write_pct: pro zent an gesamten writes, summe von write_pct = 100% --if there is a large number of writes to the temporary tablespace -you can increase sort_area_size --###### ############################################################################ ### ######## -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -drop table tot_read_writes ; create table tot_read_writes as select sum(phyrds) phys_reads, sum(phywrts) ph ys_wrts from v$filestat; spool show_io_activity.lst ttitle left 'disk i/o s by d atafile' skip 2 column column column column column select name format a40 headin g "filename" phyrds format 999,999,999 heading "reads|number" phywrts format 999 ,999,999 heading "writes|number" read_pct format 999.99 heading "reads|in [%]" w rite_pct format 999.99 heading "writes|in [%]" name, phyrds, phyrds * 100 / trw. phys_reads read_pct, phywrts, phywrts * 100 / trw.phys_wrts write_pct from tot_r ead_writes trw, v$datafile df, v$filestat fs where df.file# = fs.file# order by phyrds desc; spool off; set feed on echo off termout on pages 24 verify on ttitl e off -######################################################################### ######### ########### --- %purpose: show dbms_jobs for all oracle users --- use: needs oracle dba access --##################################################### ############################# ########### -ttitle off; select substr(job,1,4) "j ob", substr(log_user,1,5) "user", substr(schema_user,1,5) "schema",

-############################################################################### ### ########### --- %purpose: show data dictionary cache hit % for active instan ce since last startup --######################################################## ########################## ########### --- der data dictionary cache ist teil de s shared pools. nach dem instance -- startup werden die data dictionary informat ionen ins memory geladen. -- nach einer gewissen betriebszeit sollte sich ein st abiler zustand -- einstellen. der data dictionary cache miss sollte kleiner als 10 % sein. --################################################################### ############### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'show data dictionary cache hit %' skip 2 select (1- (sum(getmisses)/sum(ge ts))) * 100 "data dictionary cache hit %" from v$rowcache; -#################### ############################################################## ########### --- % purpose: show database space used for all schema-owners --###################### ############################################################ ########### -spool show_used_space_by_users.lst ttitle skip 2 left 'used space for each oracle user ' substr(to_char(last_date,'dd.mm.yyyy hh24:mi'),1,16) "last date", substr(to_char (next_date,'dd.mm.yyyy hh24:mi'),1,16) "next date", substr(broken,1,2) "b", subs tr(failures,1,6) "failed", substr(what,1,20) "command" from dba_jobs; set feed off set linesize 80 set pagesize 5000

set underline '-' break on owner skip 1 on tablespace_name on segment_type colum n owner format a16 heading 'owner' column segment_type format a10 heading 'objec t' column tablespace_name format a26 heading 'tablespace' column bytes format 9, 999,999,999 heading 'used space|[bytes]' column blocks format 999,999 heading 'u sed space|[blocks]' compute sum of bytes blocks on owner --- count space for eac h oracle object -select substr(owner,1,16) owner, substr(tablespace_name,1,26) t ablespace_name, substr(segment_type,1,10) segment_type, sum(bytes) bytes, sum(bl ocks) blocks from sys.dba_extents group by substr(owner,1,16), substr(tablespace _name,1,26), substr(segment_type,1,10) order by 1,2,3; clear breaks clear comput es clear column spool off; -#################################################### ############################## ########### --- %purpose: show database triggers for schema owner --############################################################# ##################### ########### -accept user_namen char prompt 'schema owner: ' -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -spool show_trigger.lst ttitle off column column column column column column trigger_name format a20 heading 'trig ger|name' trigger_type format a20 heading 'trigger|typ' table_owner format a10 h eading 'table|owner' table_name noprint new_value tab table_name format a20 head ing 'table|name' triggering_event format a20 heading 'event'

column status format a8 heading 'status' ttitle left 'trigger of tabelle: 'tab s kip 2 break on table_name skip page on owner skip 2 on constraint_name skip sele ct distinct table_owner, table_name, trigger_name, trigger_type, triggering_even t, status from dba_triggers where table_owner like upper('&user_namen'); spool o ff; -########################################################################### ####### ########### --- %purpose: show file-i/o rate, system-i/o rate and throug hput on all db-files --######################################################### ######################### ########### --file i/o rate --- das file i/o rate diag ramm zeigt die anzahl physical reads -- und writes pro sekunde der oracle datenb ankfiles der gesamten instance. --system i/o rate --- das system i/o rate diagra mm zeigt die anzahl logischen und physischen -- reads sowie die anzahl block nderu ngen pro sekunde. --throughput --- das diagramm zeigt die anzahl user calls und transaktionen pro -- sekunde der gesamten instance. --########################## ######################################################## ########### -set feed o ff; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'file i/o rate' skip 2

select sum(phyrds), sum(phywrts) from v$filestat; ttitle left 'system i/o rate' skip 2 select (sum(decode(name,'db block gets', value,0)) + sum(decode(name,'con sistent gets', value,0))) "block gets+consistent gets", sum(decode(name,'db bloc k changes', value,0)) "db block changes", sum(decode(name,'physical reads', valu e,0)) "physical reads" from v$sysstat; ttitle left 'throughput' skip 2 select su m(decode(name,'user commits', value,0)) "user commits", sum(decode(name,'user ca lls', value,0)) "user calls" from v$sysstat; -################################## ################################################ ########### --- %purpose: show foreign-key refrences from / to oracle tables --- use: needs oracle dba access -############################################################################### ### ########### -spool obj_dependencies.lst set feed off set pagesize 10000 ttit le off break on owner on referenced_type on referenced_name on type skip 1 colum n datum new_value datum noprint column owner format a10 heading 'object|owner' c olumn name format a24 heading 'object|name' column type format a10 heading 'obje ct|type' column referenced_name format a22 heading 'parent|name' column referenc ed_type format a10 heading 'parent|type' ttitle center 'dependencies to/from all objects' skip 2 select to_char(sysdate, 'mm/dd/yy') datum, substr(owner,1,10) o wner, substr(referenced_type,1,10) referenced_type, substr(referenced_name,1,22) referenced_name, substr(type,1,10) type, substr(name,1,24) name from dba_depend encies where owner not in ('sys','system') and referenced_type not in ('non-exis tent') order by 1,2,3,4,5,6; spool off;

exit; -######################################################################### ######### ########### --- %purpose: show foreign-primarykey relations with forei gn keys without an index --the scripts below provide information on foreign key -usage. the first script lists the foreign keys and the -second lists foreign ke ys that are missing indexes on -the foreign key columns in the child table. if t he index -is not in place, share lock problems may occur on the -parent table. -############################################################################### ### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 20 0; set heading on; set tab on; set scan on; set verify off; -spool show_foreign_ keys.lst ttitle off; column tab_owner format a10 heading "owner"; column tab_nam e_fk format a15 heading "fk-table"; column col_name_fk format a15 heading "fk-co lumn"; column tab_name_pk format a15 heading "pk-table"; column col_name_pk form at a15 heading "pk-column" -ttitle left 'foreign key listing' skip 2 break on ta b_owner on tab_name_fk skip select a.owner tab_owner, a.table_name tab_name_fk, c.column_name col_name_fk, b.table_name tab_name_pk, d.column_name col_name_pk d ba_constraints a, dba_constraints b, dba_cons_columns c, dba_cons_columns d a.r_ constraint_name = b.constraint_name a.constraint_type = 'r' b.constraint_type = 'p' a.r_owner=b.owner a.constraint_name = c.constraint_name b.constraint_name=d. constraint_name a.owner = c.owner a.table_name=c.table_name b.owner = d.owner a. owner not in ('sys','system') b.table_name=d.table_name from where and and and and and and and and and and

order by 1,2,3; -select acc.owner||'-> '||acc.constraint_name||'('||acc.column_n ame ||'['||acc.position||'])'||' ***** missing index' "indexes missing on child table" from all_cons_columns acc, all_constraints ac where ac.constraint_name = acc.constraint_name and ac.constraint_type = 'r' and acc.owner not in ('sys','sy stem') and (acc.owner, acc.table_name, acc.column_name, acc.position) in (select acc.owner, acc.table_name, acc.column_name, acc.position from all_cons_columns acc, all_constraints ac where ac.constraint_name = acc.constraint_name and ac.co nstraint_type = 'r' minus select table_owner, table_name, column_name, column_po sition from all_ind_columns) order by acc.owner, acc.constraint_name, acc.column _name, acc.position; spool off; set feed on echo off termout on pages 24 verify on ttitle off -################################################################# ################# ########### --- %purpose: show free list hit ratio in % to ver ify database block contention --################################################ ################################## ########### --- das diagramm free list hit % ze igt informationen zur datenblock -- contention. f r jedes segment unterh lt oracle e in oder mehrere freelists. -- freelists enthalten allozierte datenblocks f r diese n segment- extent mit -- freiem platz f r INSerts. bei vielen concurrent inserts s ind unter -- umst nden mehrere freelists zu erstellen. --######################### ######################################################### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'free list hit%' skip 2 select fr om where and (sum(value)-(sum(count)/2))/sum(value)*100 "gets" v$waitstat w, v$s ysstat s w.class='free list' s.name in ('db block gets', 'consistent gets');

select (sum(count) / (sum(value))) * 100 "misses" from v$waitstat w, v$sysstat s where w.class='free list' and s.name in ('db block gets', 'consistent gets'); ################################################################################ ## ########### --- %purpose: show highwater mark of a table (choose table and sc hema owner) --- calculate highwatermark as follows or use package dbms_space.unu sed_space --- select blocks -from dba_segments -- where owner = 'ppb' -and segme nt_name = 'acm'; --- select empty_blocks -from dba_tables -- where owner = 'ppb' -and table_name = 'acm'; --- highwatermark := blocks - empty_blocks -1; --- bei spiel: ausgangslage der tabelle test -- ---------------------------------------total blocks = 440 -- total bytes = 1802240 -- unused blocks = 15 -- unused byt es = 61440 -- highwater mark = (440 - 15 - 1) = 424 --- alter table test dealloc ate unused; /* ver ndert unused blocks und bytes */ --- total blocks = 425 -- tota l bytes = 1740800 -- unused blocks = 0 -- unused bytes = 0 -- highwater mark = ( 425 - 0 - 1) = 424 --- delete from test; /* ver ndert hwm nicht, select count(*) g eht lange ! */ --- total blocks = 425 -- total bytes = 1740800 -- unused blocks = 0 -- unused bytes = 0 -- highwater mark = (425 - 0 - 1) = 424 --- truncate tab le test; /* reset der hwm, select count(*) geht schnell ! */ --- total blocks = 20 -- total bytes = 81920 -- unused blocks = 19 -- unused bytes = 77824 -- highw ater mark = (20 - 19 - 1) = 0 ---

################################################################################ ## ########### -set serveroutput on size 200000 set echo off set feedback off se t verify off set showmode off set linesize 500 -accept l_user char prompt 'schem aowner: ' accept l_table char prompt 'tablename: ' -declare op1 number; op2 numb er; op3 number; op4 number; op5 number; op6 number; op7 number; hwm number; begi n dbms_space.unused_space(upper('&&l_user'),upper('&&l_table'),'table',op1,op2,o p 3,op4,op5,op6,op7); hwm := op1 - op3 - 1; dbms_output.put_line('-------------------------'); dbms_output.put_line('total blocks = '||op1); dbms_output.put_li ne('total bytes = '||op2); dbms_output.put_line('unused blocks = '||op3); dbms_o utput.put_line('unused bytes = '||op4); dbms_output.put_line('highwater mark = ( '||op1||' - '||op3||' - 1) = '|| hwm); end; / -################################# ################################################# ########### --- %purpose: show hit-ratios, consistent-gets, db-block-gets, physical-reads for the sessions --# ################################################################################ # ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -spool show_session_hi t_ratio.lst ttitle 'user hit ratios' -

skip 2 column nl newline; column "hit ratio" format 999.99 column "user session" format a15; set pagesize 999 select se.username||'('|| se.sid||')' "user sessio n", sum(decode(name, 'consistent gets',value, 0)) "consis gets", sum(decode(name , 'db block gets',value, 0)) "db blk gets", sum(decode(name, 'physical reads',va lue, 0)) "phys reads", (sum(decode(name, 'consistent gets',value, 0)) + sum(deco de(name, 'db block gets',value, 0)) sum(decode(name, 'physical reads',value, 0)) ) / (sum(decode(name, 'consistent gets',value, 0)) + sum(decode(name, 'db block gets',value, 0)) ) * 100 "hit ratio" from v$sesstat ss, v$statname sn, v$session se where ss.sid = se.sid and sn.statistic# = ss.statistic# and value != 0 and s n.name in ('db block gets', 'consistent gets', 'physical reads') group by se.use rname, se.sid having (sum(decode(name, 'consistent gets',value, 0)) + sum(decode (name, 'db block gets',value, 0)) sum(decode(name, 'physical reads',value, 0))) / (sum(decode(name, 'consistent gets',value, 0)) + sum(decode(name, 'db block ge ts',value, 0)) ) * 100 < 100; spool off; set feed on echo off termout on pages 2 4 verify on ttitle off -######################################################## ########################## ########### --- %purpose: show i/o between db-server and clients over sql*net in bytes/s --- purpose: network bytes rate --- das diag ramm network bytes rate zeigt die anzahl bytes / sekunde an -- daten, die vom date nbank server und seinen clients ber Sql*net -- ausgetauscht werden. --network i/o rate --- das diagramm network i/o rate zeigt die anzahl message -- packete / seku nde die vom datenbank server und seinen clients -- ber Sql*net ausgetauscht werde n. --########################################################################### ####### ########### -set feed off; set pagesize 10000;

set wrap off; set linesize 200; set heading on; set tab on; set scan on; set ver ify off; -ttitle left 'network bytes rate' skip 2 column sum_value format 999,99 9,999,999 heading 'sum bytes' column total_waits format 999,999,999,999 heading 'total waits ms' select sum(value) sum_value from v$sysstat where name like 'byt es%sql*net%'; ttitle left 'network i/o rate' skip 2 select sum(total_waits) tota l_waits from v$system_event where event like 'sql*net%'; -###################### ############################################################ ########### --- %pu rpose: show initial, next, total extents, total blocks of db-objects --######### ######################################################################### ###### ##### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set hea ding on; set tab on; set scan on; set verify off; -spool show_object_storage_inf o.lst ttitle 'object storage information' skip 2 select substr(s.owner,1,20) || '.' ||substr(s.segment_name,1,20) "object name", substr(s.segment_type,1,10) "ty pe", substr(s.tablespace_name,1,10) tspace, nvl(nvl(t.initial_extent, i.initial_ extent),r.initial_extent) "fstext", nvl(nvl(t.next_extent,i.next_extent),r.next_ extent) "nxtext", s.extents "totext", s.blocks "totblks" from dba_rollback_segs r, dba_indexes i, dba_tables t, dba_segments s where s.segment_type in

('cache','cluster','index','rollback','table','temporary') and s.owner not in (' system') and s.owner = t.owner (+) and s.segment_name = t.table_name (+) and s.t ablespace_name = t.tablespace_name (+) and s.owner = i.owner (+) and s.segment_n ame = i.index_name (+) and s.tablespace_name = i.tablespace_name (+) and s.owner = r.owner (+) and s.segment_name = r.segment_name (+) and s.tablespace_name = r .tablespace_name (+) order by 2,1; spool off; set feed on echo off termout on pa ges 24 verify on ttitle off -################################################### ############################### ########### --- %purpose: show indexes for a sch ema owner --- use: needs oracle dba access --################################### ############################################### ########### -spool show_indexes. lst set pause off set feed off; set pagesize 10000; set wrap off; set linesize 2 00; set heading on; set tab on; set scan on; set verify off; column column colum n column column column index_name format a25 wrap heading 'index|name' uni forma t a5 heading 'uniq-|ness' tablespace_name format a10 wrap heading 'tablespace' t able_name noprint new_value tab column_name format a26 heading 'column|name' tab le_owner format a10 heading 'table|owner' ttitle left 'indexes of tabelle: 'tab skip 2 accept user_namen char prompt 'sche ma owner: ' break on table_name skip page on table_owner skip 2 on index_name sk ip on uni on tablespace_name select i.table_owner, i.index_name, c.table_name,

c.column_name, decode(i.uniqueness,'unique','yes','nonunique','no','???') uni, i .tablespace_name from dba_ind_columns c, dba_indexes i where i.table_name = c.ta ble_name and i.index_name = c.index_name and i.table_name like upper('%') and i. table_owner = c.table_owner and i.table_owner like upper('&user_namen') order by i.table_owner, c.table_name, i.uniqueness desc, c.index_name, c.column_position ; spool off; -################################################################## ################ ########### --- %purpose: show library cache hit % for the shar ed pool of the instance --###################################################### ############################ ########### --- der library cache ist teil des shar ed pools. -- cache misses im library cache sind sehr teuer , da das sql-statement - geladen, geparst und ausgef hrt werden muss. hier gilt die regel, dass -- 99 % a ller sql-statements in geparster form im memory vorliegen m ssen. -- ist dies nich t der fall so muss der wert shared_pool_size erh ht werden. --#################### ############################################################## ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; se t tab on; set scan on; set verify off; -ttitle left 'show library cache hit %' s kip 2 select (1-(sum(reloads)/sum(pins))) *100 "library cache hit %" from v$libr arycache; -##################################################################### ############# ########### --- %purpose: show low-level locks (latches) on intern al shared memory structures --################################################## ################################ ###########

-set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading o n; set tab on; set scan on; set verify off; -ttitle left 'latch statistics' skip 2 select substr(ln.name,1,30) "name",l.gets,l.misses,l.sleeps, l.immediate_gets "immgets",l.immediate_misses "immmiss" from v$latch l, v$latchname ln, v$latchh older lh where l.latch#=ln.latch# and l.addr=lh.laddr(+) order by l.level#, l.la tch#; -######################################################################### ######### ########### --- %purpose: show memory sort hit % (memory and disc) --# ################################################################################ # ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'show mem ory sort hit %' skip 2 select (sum(decode(name, 'sorts (memory)', value, 0)) / ( sum(decode(name, 'sorts (memory)', value, 0)) + sum(decode(name, 'sorts (disk)', value, 0)))) * 100 "memory sort hit %" from v$sysstat; -####################### ########################################################### ########### --- %pur pose: show number of logswitches per hour and day as a histogram --- use: needs oracle dba access --############################################################ ###################### ########### --

### version for oracle 7 set feed off; set pagesize 10000; set wrap off; set lin esize 200; set heading on; set tab on; set scan on; set verify off; -spool show_ logswitches.lst ttitle left 'redolog file status aus v$log' skip 2 select group# , sequence#, members, archived, status, first_time from v$log; ttitle left 'anza hl logswitches pro stunde' skip 2 select substr(time,1,5) day, to_char(sum(decod e(substr(time,10,2),'00',1,0)),'99') to_char(sum(decode(substr(time,10,2),'01',1 ,0)),'99') to_char(sum(decode(substr(time,10,2),'02',1,0)),'99') to_char(sum(dec ode(substr(time,10,2),'03',1,0)),'99') to_char(sum(decode(substr(time,10,2),'04' ,1,0)),'99') to_char(sum(decode(substr(time,10,2),'05',1,0)),'99') to_char(sum(d ecode(substr(time,10,2),'06',1,0)),'99') to_char(sum(decode(substr(time,10,2),'0 7',1,0)),'99') to_char(sum(decode(substr(time,10,2),'08',1,0)),'99') to_char(sum (decode(substr(time,10,2),'09',1,0)),'99') to_char(sum(decode(substr(time,10,2), '10',1,0)),'99') to_char(sum(decode(substr(time,10,2),'11',1,0)),'99') to_char(s um(decode(substr(time,10,2),'12',1,0)),'99') to_char(sum(decode(substr(time,10,2 ),'13',1,0)),'99') to_char(sum(decode(substr(time,10,2),'14',1,0)),'99') to_char (sum(decode(substr(time,10,2),'15',1,0)),'99') to_char(sum(decode(substr(time,10 ,2),'16',1,0)),'99') to_char(sum(decode(substr(time,10,2),'17',1,0)),'99') to_ch ar(sum(decode(substr(time,10,2),'18',1,0)),'99') to_char(sum(decode(substr(time, 10,2),'19',1,0)),'99') to_char(sum(decode(substr(time,10,2),'20',1,0)),'99') to_ char(sum(decode(substr(time,10,2),'21',1,0)),'99') to_char(sum(decode(substr(tim e,10,2),'22',1,0)),'99') to_char(sum(decode(substr(time,10,2),'23',1,0)),'99') f rom v$log_history group by substr(time,1,5) / spool off; ### version for oracle 8.1.x set set set set set feed off; pagesize 10000; wrap off; linesize 200; head ing on; "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"

set tab on; set scan on; set verify off; -spool show_logswitches.lst ttitle left 'redolog file status from v$log' skip 2 select group#, sequence#, members, arch ived, status, first_time from v$log; ttitle left 'number of logswitches per hour ' skip 2 select to_char(first_time,'yyyy.mm.dd') day, to_char(sum(decode(substr( to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'00' ,1,0)),'99') "00", to_char(sum (decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'01' ,1,0)),'99') "0 1", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'02' ,1,0)),'99') "02", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:m i'),10,2),'03' ,1,0)),'99') "03", to_char(sum(decode(substr(to_char(first_time,' ddmmyyyy:hh24:mi'),10,2),'04' ,1,0)),'99') "04", to_char(sum(decode(substr(to_ch ar(first_time,'ddmmyyyy:hh24:mi'),10,2),'05' ,1,0)),'99') "05", to_char(sum(deco de(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'06' ,1,0)),'99') "06", t o_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'07' ,1,0) ),'99') "07", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),1 0,2),'08' ,1,0)),'99') "08", to_char(sum(decode(substr(to_char(first_time,'ddmmy yyy:hh24:mi'),10,2),'09' ,1,0)),'99') "09", to_char(sum(decode(substr(to_char(fi rst_time,'ddmmyyyy:hh24:mi'),10,2),'10' ,1,0)),'99') "10", to_char(sum(decode(su bstr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'11' ,1,0)),'99') "11", to_cha r(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'12' ,1,0)),'99 ') "12", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2), '13' ,1,0)),'99') "13", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:h h24:mi'),10,2),'14' ,1,0)),'99') "14", to_char(sum(decode(substr(to_char(first_t ime,'ddmmyyyy:hh24:mi'),10,2),'15' ,1,0)),'99') "15", to_char(sum(decode(substr( to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'16' ,1,0)),'99') "16", to_char(sum (decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'17' ,1,0)),'99') "1 7", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'18' ,1,0)),'99') "18", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:m i'),10,2),'19' ,1,0)),'99') "19", to_char(sum(decode(substr(to_char(first_time,' ddmmyyyy:hh24:mi'),10,2),'20' ,1,0)),'99') "20", to_char(sum(decode(substr(to_ch ar(first_time,'ddmmyyyy:hh24:mi'),10,2),'21'

,1,0)),'99') "21", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:m i'),10,2),'22' ,1,0)),'99') "22", to_char(sum(decode(substr(to_char(first_time,' ddmmyyyy:hh24:mi'),10,2),'23' ,1,0)),'99') "23" from v$log_history group by to_c har(first_time,'yyyy.mm.dd') / spool off; ### version for oracle 8.1.x with arch ived redologs alter session set nls_date_format = 'dd.mm.yyyy:hh24:mi'; spool sh ow_logswitches.lst ttitle left 'redolog file status from v$log' skip 2 select gr oup#, sequence#, members, archived, status, first_time from v$log; ttitle left ' number of logswitches per hour' skip 2 select substr(completion_time,1,5) day, t o_char(sum(decode(substr(completion_time,12,2),'00',1,0)),'99') to_char(sum(deco de(substr(completion_time,12,2),'01',1,0)),'99') to_char(sum(decode(substr(compl etion_time,12,2),'02',1,0)),'99') to_char(sum(decode(substr(completion_time,12,2 ),'03',1,0)),'99') to_char(sum(decode(substr(completion_time,12,2),'04',1,0)),'9 9') to_char(sum(decode(substr(completion_time,12,2),'05',1,0)),'99') to_char(sum (decode(substr(completion_time,12,2),'06',1,0)),'99') to_char(sum(decode(substr( completion_time,12,2),'07',1,0)),'99') to_char(sum(decode(substr(completion_time ,12,2),'08',1,0)),'99') to_char(sum(decode(substr(completion_time,12,2),'09',1,0 )),'99') to_char(sum(decode(substr(completion_time,12,2),'10',1,0)),'99') to_cha r(sum(decode(substr(completion_time,12,2),'11',1,0)),'99') to_char(sum(decode(su bstr(completion_time,12,2),'12',1,0)),'99') to_char(sum(decode(substr(completion _time,12,2),'13',1,0)),'99') to_char(sum(decode(substr(completion_time,12,2),'14 ',1,0)),'99') to_char(sum(decode(substr(completion_time,12,2),'15',1,0)),'99') t o_char(sum(decode(substr(completion_time,12,2),'16',1,0)),'99') to_char(sum(deco de(substr(completion_time,12,2),'17',1,0)),'99') to_char(sum(decode(substr(compl etion_time,12,2),'18',1,0)),'99') to_char(sum(decode(substr(completion_time,12,2 ),'19',1,0)),'99') to_char(sum(decode(substr(completion_time,12,2),'20',1,0)),'9 9') to_char(sum(decode(substr(completion_time,12,2),'21',1,0)),'99') to_char(sum (decode(substr(completion_time,12,2),'22',1,0)),'99') to_char(sum(decode(substr( completion_time,12,2),'23',1,0)),'99') from v$archived_log group by substr(compl etion_time,1,5) / spool off; "00", "01", "02", "03", "04", "05", "06", "07", "08 ", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" -############################################################################### ### ########### --

-- %purpose: show number of objects (tab,ind,syn,vew,seq,prc,fun,pck,trg) for ea ch oracle user --- use: needs oracle dba access --############################## #################################################### ########### --- version for oracle7/8 -set feed off; set pagesize 10000; set wrap off; set linesize 200; se t heading on; set tab on; set scan on; set verify off; column column column colu mn column column column column column column tab ind syn vew seq prc fun pck trg dep format format format format format format format format format format 9999 9999 9999 9999 9999 9999 9999 9999 9999 9999 heading heading heading heading hea ding heading heading heading heading heading "tab" "ind" "syn" "vew" "seq" "prc" "fun" "pck" "trg" "dep" spool list_objects_by_user.lst ttitle 'object count by user' skip 2 select subst r(username,1,10) "user", count(decode(o.type, 2, o.obj#, '')) tab, count(decode( o.type, 1, o.obj#, '')) ind, count(decode(o.type, 5, o.obj#, '')) syn, count(dec ode(o.type, 4, o.obj#, '')) vew, count(decode(o.type, 6, o.obj#, '')) seq, count (decode(o.type, 7, o.obj#, '')) prc, count(decode(o.type, 8, o.obj#, '')) fun, c ount(decode(o.type, 9, o.obj#, '')) pck, count(decode(o.type,12, o.obj#, '')) tr g, count(decode(o.type,10, o.obj#, '')) dep from sys.obj$ o, sys.dba_users u whe re u.user_id = o.owner# (+) and o.type > 0 group by username; spool off set feed on echo off termout on pages 24 verify on --- version for oracle8i -set feed of f;

set set set set set set set pagesize 10000; wrap off; linesize 200; heading on; tab on; scan on; verify off; tab ind syn vew seq prc fun pck trg dep format format format format format form at format format format format 9999 9999 9999 9999 9999 9999 9999 9999 9999 9999 heading heading heading heading heading heading heading heading heading heading "tab" "ind" "syn" "vew" "seq" "prc" "fun" "pck" "trg" "dep" column column column column column column column column column column spool list_objects_by_user.lst ttitle 'object count by user' skip 2 select subst r(username,1,10) "user", count(decode(o.type#, 2, o.obj#, '')) tab, count(decode (o.type#, 1, o.obj#, '')) ind, count(decode(o.type#, 5, o.obj#, '')) syn, count( decode(o.type#, 4, o.obj#, '')) vew, count(decode(o.type#, 6, o.obj#, '')) seq, count(decode(o.type#, 7, o.obj#, '')) prc, count(decode(o.type#, 8, o.obj#, '')) fun, count(decode(o.type#, 9, o.obj#, '')) pck, count(decode(o.type#,12, o.obj# , '')) trg, count(decode(o.type#,10, o.obj#, '')) dep from sys.obj$ o, sys.dba_u sers u where u.user_id = o.owner# (+) and o.type# > 0 group by username; spool o ff set feed on echo off termout on pages 24 verify on -######################### ######################################################### ########### --- %purpo se: show number of rows per block for a table (only for oracle7 rowid) --####### ########################################################################### #### ####### -set echo off set feedback off set verify off set showmode off set pages ize 5000 set linesize 500 -accept l_table char prompt 'tablename: '

-spool show_rows_per_block_ora7.lst ttitle left 'table rows per block' skip 2 -s elect substr(t.rowid,1,8) || '-' || substr(t.rowid,15,4) "block", count(*) "rows _per_block" from &&l_table t where rownum < 2000 group by substr(t.rowid,1,8) || '-' || substr(t.rowid,15,4); spool off; -###################################### ############################################ ########### --- %purpose: show numb er of transactions and other cursor statistics (commits, rollbacks, etc) --- use : needs oracle dba access --#################################################### ############################## ########### -set feed off; set pagesize 10000; se t wrap off; set linesize 200; set heading on; set tab on; set scan on; set verif y off; -column statistic# format 999 heading 'id' column na format a32 heading ' statistic' column ppe format 99990.90 column nr_tx format 99999990 column nr_rec c format 99990.90 ttitle spool set select from where or left 'monitor cursor act ivites' skip 2 cursor_activites.log termout on rpad (name, 32, '.') as na, value v$sysstat name like '%cursor%' name in ('parse count', 'execute count', 'user c alls', 'user commits', 'user rollbacks', 'parse time cpu', 'parse time elapsed', 'recursive calls') /

ttitle select from where and left 'number of transactions' skip 2 a.value + b.value as nr_tx v$sysstat a, v$s ysstat b a.name = 'user commits' b.name = 'user rollbacks' left 'recursive call per user call' skip 2 c.value / d.value as nr_recc v$sysstat c, v$sysstat d c.na me = 'recursive calls' d.name = 'user calls' left 'parse per execute [%]' skip 2 e.value / f.value * 100.0 as ppe v$sysstat e, v$sysstat f e.name = 'parse count ' f.name = 'execute count' / ttitle select from where and / ttitle select from where and / spool off ttitle off -########################################################## ######################## ########### --- %purpose: show number of physical reads and writes per sec for each db-file (i/o details) --########################### ####################################################### ########### -set feed of f; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab o n; set scan on; set verify off; -ttitle left 'file i/o rate details since last i nstance startup' skip 2 select from where order -substr(name,1,30) "name",phyrds ,phywrts,phyblkrd,phyblkwrt v$dbfile df, v$filestat fs df.file#=fs.file# by name ;

################################################################################ ## ########### --- %purpose: show object privileges for schema owner which can b e choosen --- use: needs oracle dba access --################################### ############################################### ########### -set feed off; set p agesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set s can on; set verify off; spool show_grants.lst ttitle off accept user_namen char prompt 'schema owner: ' column column column column column owner format a10 head ing 'object|owner' grantor format a22 heading 'user who|performed the grant' gra ntee format a24 heading 'user/role to whom|access was granted' privilege format a12 heading 'object|privilege' table_name noprint new_value tab ttitle left 'object grants on: 'tab skip 2 break on table_name skip page on owne r skip 2 on grantor skip on grantee on privileges select substr(table_name,1,20) table_name, substr(owner,1,16) owner, substr(grantor,1,24) grantor, substr(gran tee,1,24) grantee, substr(privilege,1,12) privilege from dba_tab_privs where upp er(owner) like upper('&user_namen') order by 1,2,3,4,5; spool off; -############ ###################################################################### ######### ## --- %purpose: show objects and comments from the oracle data dictionary (view dictionary) --- use: needs oracle dba access ---

################################################################################ ## ########### -set termout on; set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading off; set tab on; set scan on; set verify off; spoo l show_dictionary.lst select substr(table_name,1,20) "table name", substr(commen ts,1,100) "comment" from dictionary order by table_name; spool off; -########### ####################################################################### ######## ### --- %purpose: show objects which cannot allocate next extent (ora-01653) --alter table credit allocate extent; -- ora-01653: unable to extend table ppb.cr edit by 5000 in tablespace cre --############################################### ################################### ########### -set feed off; set pagesize 1000 0; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -spool show_objects_no_next_extent.lst ttitle 'show objects which ca nnot allocate the next extent' skip 2 column column column column column owner f ormat a10; segment_name format a22; segment_type format a10; tablespace_name for mat a14; next_extent format 999,999,999; select seg.owner, seg.segment_name, seg.segment_type, seg.tablespace_name, t.nex t_extent from sys.dba_segments seg, sys.dba_tables t where (seg.segment_type = ' table' and seg.segment_name = t.table_name

and and union select seg.owner, seg.segment_name, seg.segment_type, seg.tablespace_name, decode (seg.segment_type, 'cluster', c.next_extent) from sys.dba_segments seg, sys.dba_clusters c where (seg.segment_type = 'cluster' and seg.segment_name = c. cluster_name and seg.owner = c.owner and not exists (select tablespace_name from dba_free_space free where free.tablespace_name = c.tablespace_name and bytes >= c.next_extent )) union select seg.owner, seg.segment_name, seg.segment_type, se g.tablespace_name, decode (seg.segment_type, 'index', i.next_extent ) from sys.d ba_segments seg, sys.dba_indexes i where (seg.segment_type = 'index' and seg.seg ment_name = i.index_name and seg.owner = i.owner and not exists (select tablespa ce_name from dba_free_space free where free.tablespace_name = i.tablespace_name and bytes >= i.next_extent )) union select seg.owner, seg.segment_name, seg.segm ent_type, seg.tablespace_name, decode (seg.segment_type, 'rollback', r.next_exte nt) from sys.dba_segments seg, sys.dba_rollback_segs r where (seg.segment_type = 'rollback' and seg.segment_name = r.segment_name and seg.owner = r.owner and no t exists (select tablespace_name from dba_free_space free where free.tablespace_ name = r.tablespace_name and bytes >= r.next_extent )) / ttitle 'segments that a re sitting on the maximum extents allowable' skip 2 select e.owner, e.segment_na me, e.segment_type, count(*), avg(max_extents) from dba_extents e, dba_segments s where e.segment_name = s.segment_name seg.owner not exists (select from where and = t.owner tablespace_name dba_free_space free free.tablespace_name = bytes >= t.tablespace_name t.next_extent ))

and e.owner = s.owner group by e.owner, e.segment_name, e.segment_type having co unt(*) = avg(max_extents) / spool off; set feed on echo off termout on pages 24 verify on ttitle off -########################################################## ######################## ########### --- %purpose: show partition indexes (dba_i nd_columns, dba_indexes) --- use: needs oracle dba access --#################### ############################################################## ########### -set feed off; set pagesize 100000; set wrap off; set linesize 200; set heading on; s et tab on; set scan on; set verify off; spool show_part_indexes.lst set pause of f column column column column column index_name format a25 wrap heading 'index|n ame' uni format a5 heading 'uniq-|ness' table_name noprint new_value tab column_ name format a30 heading 'column|name' table_owner format a10 heading 'table|owne r' ttitle left 'partitioned indexes of table: 'tab skip 2 break on table_name skip page on table_owner skip 2 on index_name skip select i.table_owner, i.index_name , c.table_name, c.column_name, decode(i.uniqueness,'unique','yes','nonunique','n o','???') uni from dba_ind_columns c, dba_indexes i where i.table_name = c.table _name and i.index_name = c.index_name and i.table_name like upper('%') and i.tab le_owner = c.table_owner and i.partitioned = 'yes' order by i.table_owner, c.tab le_name,

i.uniqueness desc, c.index_name, c.column_position; spool off; set feed on echo off termout on pages 24 verify on; ttitle off; -################################ ################################################## ########### --- %purpose: sho w partition tables and indexes (dba_tab_partitions) --- use: needs oracle dba ac cess --######################################################################### ######### ########### -set feed off; set pagesize 100000; set wrap off; set line size 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'show partition tables' skip 2 set linesize 200 set pagesize 500 column table_na me format a20 heading "table|name" column index_name format a20 heading "index|n ame" column partition_name format a20 heading "partition|name" column tablespace _name format a10 heading "tablespace" column partition_position format 999999 he ading "partition|position" break on table_name; spool show_partition_tables.lst select table_name, partition_name, partition_position, tablespace_name from dba_ tab_partitions order by table_name,partition_position; break on index_name; sele ct index_name, partition_name, partition_position, tablespace_name from dba_ind_ partitions order by index_name,partition_position;

spool off set feed on echo off termout on pages 24 verify on; ttitle off; -##### ############################################################################# ## ######### --- %purpose: show primary and foreign key relationsships --- use: nee ds oracle dba access --######################################################### ######################### ########### -spool show_fk_pk_relations.lst set feed o ff set pagesize 10000 ttitle off -ttitle left 'primary and foreign key relations ships' skip 2 set feed off set pagesize 10000 -column datum new_value datum nopr int column for_owner format a5 heading 'table|owner' column pri_tsname format a1 0 heading 'tablespace' column for_table format a17 heading 'from|foreign|table' column for_col format a16 heading 'from|foreign|column' column pri_table format a17 heading 'to|primary|table' column pri_col format a16 heading 'to|primary|col umn' break on for_owner skip 1 select a.owner for_owner, e.tablespace_name pri_t sname, a.table_name for_table, c.column_name for_col, b.table_name pri_table, d. column_name pri_col from dba_constraints a, dba_constraints b, dba_cons_columns c, dba_cons_columns d, dba_tables e where a.owner not in ('sys','system') and a. r_constraint_name = b.constraint_name and a.constraint_type = 'r' and b.constrai nt_type = 'p' and a.r_owner = b.owner and a.constraint_name = c.constraint_name and a.owner = c.owner and a.table_name = c.table_name and b.constraint_name = d. constraint_name and b.owner = d.owner and b.table_name = d.table_name and b.tabl e_name = e.table_name order by a.owner,a.table_name; --

################################################################################ ## ########### --- %purpose: show procedures of a schema owner --############### ################################################################### ########### -accept user_namen char prompt 'schema owner: ' set feed off; set pagesize 10000 ; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set v erify off; -spool show_procedures.lst ttitle off column datum new_value datum no print column owner format a20 heading 'procedure|owner' column name format a20 h eading 'procedure|name' column type format a20 heading 'procedure|type' ttitle l eft 'defined procedures, functions, packages'skip 2 select distinct to_char(sysd ate, 'mm/dd/yy') datum, substr(owner,1,12) owner, substr(name,1,27) name, substr (type,1,27) type from dba_source where owner like upper('&user_namen') order by 1,2,3,4; spool off; -########################################################### ####################### ########### --- %purpose: show redo allocation hits in % (redolog tuning) --- redo allocation tuning --- das diagramm redo allocation hit % zeigt das buffer tuning der redolog -- file aktivit ten. die misses d rfen nicht g r sser als 1 % sein. --- das diagramm redo statistics zeigt die anzahl redo entries, space -- requests und synch. writes pro sekunde f r die datenbank instance. --### ############################################################################### ########### -set feed off; set pagesize 10000; set wrap off;

set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttit le left 'redo alloc hit%' skip 2 select ((gets+immediate_gets) / (gets+immediate _gets+misses+immediate_misses)) *100 "redo alloc hit%" from v$latch where name = 'redo allocation'; ttitle left 'redo statistics' skip 2 select sum(decode(name, 'redo entries', value,0)) "redo entries", sum(decode(name,'redo log space reques ts', value,0)) "space requests", sum(decode(name,'redo synch writes', value,0)) "synch writes" from v$sysstat; -################################################ ################################## ########### --- %purpose: show redo waits ('r edo log space wait time', 'redo log space requests') --######################### ######################################################### ########### -col name format a30 justify l heading 'redo log buffer' col value format 99,999,990 justi fy c heading 'waits' select name, value from v$sysstat where name in ('redo log space wait time','redo log space requests') / -################################# ################################################# ########### --- %purpose: show roles granted to users and roles --############################################ ###################################### ########### -spool show_roles.lst -ttitle left 'display roles granted to users and roles' skip 2 set feed off set pagesiz e 10000 break on grantee skip 1 column datum new_value datum noprint column gran tee format a27 heading 'user or role|receiving the grant'

column granted_role format a30 heading 'granted|role' column default_role format a10 heading 'default|role' column admin_option format a10 heading 'admin|option ' select to_char(sysdate, 'mm/dd/yy') datum, substr(grantee,1,27) grantee, subst r(granted_role,1,30) granted_role, substr(default_role,1,20) default_role, subst r(admin_option,1,10) admin_option from dba_role_privs where grantee not in ('sys ','system') order by 1,2,3; -################################################### ############################### ########### --- %purpose: show rollback segment report usage (nowait hit %, waits, shrinks) --################################## ################################################ ########### --- rollback nowait hit % zeigt die hits und misses f r die online rollback -- segmente. ist dieser w ert zu gross, so m ssen mehr rollbacksegmente -- erstellt werden. --rollback segme nt waits --- rollback segment waits k nnen einfach aus v$waitstat gelesen werden. -- waits auf undo header werden h ufig verringert, indem man weitere -- rollback seg mente erstellt. -- waits auf undo block werden verringert, indem man rollback segm ente -- mit mehr extents erstellt (10 - 20 extents). --rollback segments shrinks --- rollbacksegmente sollten nicht dauernd wachsen und wieder kleiner werden, - um den optimal parameter einzuhalten. dies kann mit dem folgenden query -- kon trolliert werden. extents und shrinks sollten keine auftreten, sonst -- muss der parameter optimal angepasst werden. --######################################### ######################################### ########### -set feed off; set pagesiz e 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on ; set verify off; -ttitle left 'rollback nowait hit %' skip 2

select ((sum(gets)-sum(waits)) / sum(gets)) * 100 "rollback nowait hit %" from v $rollstat; ttitle left 'rollback segment waits' skip 2 select * from v$waitstat; ttitle left 'rollback segments shrinks' skip 2 select substr(name,1,5) "name", extents, gets, waits, extends, shrinks from v$rollstat stat, v$rollname name whe re stat.usn = name.usn and status = 'online'; -################################# ################################################# ########### --- %purpose: show sql-code of cpu-intensive oracle prozesses in the memory --#################### ############################################################## ########### --- t uning an application involves tuning the sql statements that are poorly -- desig ned. while tuning applications, it is important for a dba to find out which -- s ql statements are consuming a large amount of cpu resources. -- after tracking d own these statements, the dba can tune them to consume a less -- cpu, improving response timings considerably. the script will work only on unix -- operating sy stems. --- it displays the top 10 cpu-intensive oracle processes on the -- opera ting system with the first column giving the %cpu used, the second column -- uni x pid, the third column user , the fourth column terminal, and the last -- colum n unix process. enter the unix pid at the prompt and it will display the -- stat ement belonging to that process. --- ps -eaf -o pcpu,pid,user,tty,comm | grep or a | grep -v \/sh | grep -v ora_ | sort -r | head -20 --- ####################### ###################################################### -column username format a 10 column terminal format a9 column sql_text format a30 prompt prompt prompt pro mpt enter the unix pid : accept pid -select a.username, a.terminal, a.program, b .sql_text from v$session a, v$sqlarea b, v$process c where (c.spid = '&pid' or a .process = '&pid') and a.paddr = c.addr

and a.sql_address = b.address / -############################################### ################################### ########### --- %purpose: show sql-statement s in memory for the connected sessions (shared cursors) --###################### ############################################################ ########### --- das diagramm sql area zeigt die shared cusor informationen -- im library cache. --### ############################################################################### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; s et heading on; set tab on; set scan on; set verify off; -column username format a12 heading 'user' ttitle left 'sql of connected sessions' skip 2 select distinc t nvl(username,type) username,sid,sql_text from v$session, v$sqlarea where sql_h ash_value = hash_value and sql_text is not null order by username; -############ ###################################################################### ######### ## --- %purpose: show sql-statements in memory with i/o-intensiv sql-statements (v$sqlarea) --################################################################## ################ ########### --- output from v$sqlarea: --- executions: the numb er of executions that took place on this object -since iw was brought into the l ibrary cache. --- reads_per_run: number od disk-bytes reads per execution, if th is is high, then -the statement is i/o bound. --- i/o-intensive sql-statements i n the memory (v$sqlarea)

--total read-per-run disk-reads buffergets hit -- sql-statement runs [number of] [number of] [number of] ratio [%] -- ------------------------------- -------- ------------- ----------------------- ---------- declare job binary_integer := : 1 204,670.0 204,670 47,982 ### -- declare job binary_integer := 1 77,858.0 77,8 58 181,282 57 -- select msisdn, function, modif 1 12,087.0 12,087 25,602 53 -- s elect msisdn, function, modif 1 12,031.0 12,031 25,599 53 -- select msisdn, func tion, modifi 1 11,825.0 11,825 25,598 54 -- select "a".rowid, 'ppb', 'frag 1 11, 538.0 11,538 11,542 0 -- select msisdn.ms_id ,to_char(msi 270 3,259.1 879,953 3, 939,464 78 -- select msisdn.ms_id from msis 270 3,258.0 879,656 3,939,723 78 --the last two statements are quit heavy, they runs 270 times, each time they nee ded 3000 -- disk reads, total used 870000 disk reads --######################### ######################################################### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -column sql_text format a40 heading 'sql-state ment' column executions format 999,999 heading 'total|runs' column reads_per_run format 999,999,999.9 heading 'read-per-run|[number of]' column disk_reads forma t 999,999,999 heading 'disk-reads|[number of]' column buffer_gets format 999,999 ,999 heading 'buffer-gets|[number of]' column hit_ratio format 99 heading 'hit|r atio [%]' ttitle left 'i/o-intensive sql-statements in the memory (v$sqlarea)' s kip 2 select sql_text, executions, round(disk_reads / executions, 2) reads_per_r un, disk_reads, buffer_gets, round((buffer_gets - disk_reads) / buffer_gets, 2)* 100 hit_ratio from v$sqlarea where executions > 0 and buffer_gets > 0

and (buffer_gets - disk_reads) / buffer_gets < 0.80 order by 3 desc; -########## ######################################################################## ####### #### --- %purpose: shared pool minimium size calculator --oracle server - enterp rise edition 8.1.x - 10.1.x --- use: needs oracle dba access --this script provi des the following items: current shared pool size, sum -of shared pool objects, sum of sql size, sum of user size and the minumum -suggested shared pool size fo r this instance. --fyi: if the shared_pool has been flushed recently, the -==== "minimum suggested shared pool size" may not be calculated properly. --######### ######################################################################### ###### ##### -spool minshpool.lst set numwidth 15 column shared_pool_size format 999,99 9,999 column sum_obj_size format 999,999,999 column sum_sql_size format 999,999, 999 column sum_user_size format 999,999,999 column min_shared_pool format 999,99 9,999 select to_number(value) shared_pool_size, sum_obj_size, sum_sql_size, sum_ user_size, (sum_obj_size + sum_sql_size+sum_user_size)* 1.3 min_shared_pool from (select sum(sharable_mem) sum_obj_size from v$db_object_cache where type <> 'cu rsor'), (select sum(sharable_mem) sum_sql_size from v$sqlarea), (select sum(250 * users_opening) sum_user_size from v$sqlarea), v$parameter where name = 'shared _pool_size' / spool off-######################################################## ########################## ########### --- %purpose: show system privileges of o racle-roles and db-user --###################################################### ############################ ########### -ttitle left 'output generated by: ' sq l.user ' at: ' format a8 datum -

skip skip left 'system privileges on users and roles' skip left 'oracle version ' format a15 sql.release skip 2 set feed off set pagesize 10000 break on grantee skip 1 column datum new_value datum noprint column grantee format a27 heading ' user or role|receiving the grant' column privilege format a40 heading 'system|pr ivilege' column admin_option format a10 heading 'admin|option' select to_char(sy sdate, 'mm/dd/yy') datum, substr(grantee,1,27) grantee, substr(privilege,1,40) p rivilege, substr(admin_option,1,10) admin_option from dba_sys_privs order by 1,2 ,3; -########################################################################### ####### ########### --- %purpose: show segments with critical number of extents, soon reaching max_extents --################################################### ############################### ########### -clear columns breaks computes set p agesize 100 column owner format a15 column segment_name format a20 column segmen t_type format a20 select from where and owner,segment_name,segment_type,extents, max_extents dba_segments max_extents <= 10*(extents) max_extents != 0; column owner clear column segment_name clear column segment_type clear -######## ########################################################################## ##### ###### --- %purpose: show sequences for schema owner --######################### ######################################################### ########### --

accept user_namen char prompt 'schema owner: ' set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set ve rify off; -spool show_sequences.lst ttitle off column column column column colum n column column column column column datum new_value datum noprint sequence_owne r format a20 heading 'sequence|owner' sequence_name noprint new_value sequence m in_value format 99 heading 'minimal|value ' max_value format 9.999eeee heading ' maximal |value increment_by format 99 heading 'incr|by ' last_number format 9999 999 heading 'last |number ' cache_size format 9999 heading 'cache|size ' order_f lag format a7 heading 'order ?' cycle_flag format a7 heading 'cycle ?' ' ttitle left 'properties for sequence: 'sequence skip 2 break on sequence_name sk ip page on sequence_owner skip 2 select to_char(sysdate, 'mm/dd/yy') datum, subs tr(sequence_owner,1,12) sequence_owner, substr(sequence_name,1,27) sequence_name , min_value, max_value, increment_by, last_number, cache_size, decode(order_flag , 'y','yes', 'n','no') order_flag, decode(cycle_flag, 'y','yes', 'n','no') cycle _flag from dba_sequences where sequence_owner like upper('&user_namen') order by 1,2,3,4; spool off; -########################################################## ######################## ########### --- %purpose: show session statistic (users logged-on, users waiting, users waiting-for-locks) --########################## ######################################################## ###########

--- das diagramm no. of users logged on zeigt die anzahl concurrent -- users sessi ons, unabh nig davon ob sie nun aktiv sind oder nicht. --- das diagramm no. of user s running zeigt die users sessions, -- welche eine transaktion ausf hren. --- das d iagramm no. of users waiting zeigt die user sessions, die -- auf einen event (for whatever reason) warten m ssen, um eine aktion durchzuf hren. --- das diagramm no. of users waiting for lock zeigt die user sessions, -- die auf die freigabe eines lo cks warten m ssen. --############################################################# ##################### ########### -set feed off; set pagesize 10000; set wrap of f; set linesize 200; set heading on; set tab on; set scan on; set verify off; tt itle off; -select sessions_current "users logged on" from v$license; -select cou nt(*) "users running" from v$session_wait where wait_time!=0; -ttitle left 'user s waiting' skip 2 select substr(w.sid,1,5) "sid", substr(s.username,1,15) "user" , substr(event,1,40) "event", seconds_in_wait "wait [s]" from v$session_wait w, v$session s where s.sid = w.sid and state = 'waiting' and event not like 'sql*ne t%' and event != 'client message' and event not like '%mon timer' and event != ' rdbms ipc message' and event != 'null event'; -select count(*) "users waiting fo r locks" from v$session where lockwait is not null; -########################### ####################################################### ########### --

-- %purpose: show sessions with bad buffer cache hit ratio in % --############## #################################################################### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'show sessions with ba d buffer cache hit ratio in %' skip 2 -select substr(a.username,1,12) "user", a. sid "sid", b.consistent_gets "consgets", b.block_gets "blockgets", b.physical_re ads "physreads", 100 * round((b.consistent_gets + b.block_gets - b.physical_read s) / (b.consistent_gets + b.block_gets),3) hitratio from v$session a, v$sess_io b where a.sid = b.sid and (b.consistent_gets + b.block_gets) > 0 and a.username is not null order by hitratio asc; -############################################ ###################################### ########### --- %purpose: show size of ea ch object itself (without content) in the database --show size of each object in the database. note -that not the size including the rows will be -shown for tab les, but the size for the table itself. --###################################### ############################################ ########### -set feed off; set page size 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; spool show_obyect_size.lst ttitle off; column owner format a8 heading 'object|owner' column name format a30 heading 'name' column type form at a13 heading 'type'

column column column column source_size format 99999999 heading 'source|size' parsed_size format 99999999 he ading 'parsed|size' code_size format 99999999 heading 'code|size' error_size for mat 99999999 heading 'error|size' select owner, name, type, source_size, parsed_size, code_size, error_size from m y_object_size where owner not in ('sys','system','public') order by owner,type / spool off; -################################################################### ############### ########### --- %purpose: show startup time of the oracle instan ce (different for ora7 and ora8: v$instance) --################################# ################################################# ########### --- instance start up-time for oracle-7 -select to_char(to_date(d.value,'j'),'dd.mm.yyyy')||' '|| t o_char(to_date(s.value,'sssss'),'hh24:mi:ss') startup_time from v$instance d, v$ instance s where d.key = 'startup time - julian' and s.key = 'startup time - sec onds'; --- instance startup-time for oracle-8 -select to_char(startup_time,'dd.m m.yyyy:hh24:mi:ss') startup_time from v$instance; -############################# ##################################################### ########### --- %purpose: show statistics of connected sessions (pid, connection-type, username, logon-tim e) --########################################################################### ####### ########### -col osuser format a10 trunc heading "osuser as" col orauser format a10 trunc col machine format a10 trunc col sprogram format a15 trunc col process format a20 trunc col server format a3 trunc col sess_id format 9999 col proc_id format a7 -select s.osuser osuser, s.username orauser, s.machine machin e,

s.program sprogram, p.program process, s.sid sess_id, p.spid proc_id, s.logon_ti me, s.server server from v$session s, v$process p where s.paddr = p.addr and typ e != 'background' and p.username is not null order by 6 / col osuser clear col m achine clear col orauser clear ttitle off -##################################### ############################################# ########### --- %purpose: show sta tus for all objects (valid, invalid) of a schema owner --show object of a user o r wildcard incl. status -(choice valid or invalid (default both) --############# ##################################################################### ########## # -col user_name noprint new_value user_name col date_time noprint new_value dat e_time col owner format a13 trunc col object_name format a30 col object_type for mat a8 trunc heading obj-type col status format a7 col last_ddl_time format a17 prompt prompt user name, wildcard or <return> for all users: prompt object name, wildcard or <return> for all objects: prompt v = valid, i = invalid, <return> = valid and invalid: prompt accept user_name char prompt "user name: " accept obj ect_name char prompt "object name: " accept status char prompt "status: " set ec ho off termout off pause off select upper(nvl('&&user_name','%')) user_name, to_ char(sysdate,'dd.mm.yyyy hh24:mi') date_time from dual; set termout on; set feed on; set pagesize 10000; set wrap off; set linesize 200; set tab on; set verify off set timing off ttitle left 'objects of user 'user_name' at 'date_time -

right sql.pno skip 2 spool show_object_status.lst select owner, object_name, dec ode(object_type,'package','pck-spez', 'package body','pck-body', 'database link' ,'db-link', object_type) object_type, status, to_char(last_ddl_time,'dd.mm.yy hh 24:mi:ss') last_ddl_time from sys.dba_objects where owner like nvl(upper('&user_ name'),'%') and object_name like nvl(upper('&object_name'),'%') and status like decode(upper(substr('&status',1,1)), 'v', 'valid', 'i','invalid', '%') order by owner, object_name, object_type / spool off prompt prompt show_object_status.lst has been spooled prompt -###################################################### ############################ ########### --- %purpose: show synonyms for all sch mea owners --################################################################### ############### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -spool s how_synonyms.lst break on table_owner skip 1 column datum new_value datum noprin t column owner format a12 heading 'synonym|owner' column table_owner format a12 heading 'table|owner' column table_name format a26 heading 'table|name' column s ynonym_name format a26 heading 'synonym|name' select to_char(sysdate, 'mm/dd/yy' ) datum, substr(table_owner,1,12) table_owner, substr(table_name,1,26) table_nam e, substr(synonym_name,1,26) synonym_name, substr(owner,1,12) owner from dba_syn onyms where table_owner not in ('sys','system','dbsnmp'); order by 1,2,3,4; spoo l off; --

################################################################################ ## ########### --- %purpose: show table grants for all schema owners --- use: ea ch oracle user --############################################################### ################### ########### -spool show_column_grants.lst ttitle left 'show grants on table columns' skip 2 set feed off set pagesize 10000 column column co lumn column column column owner noprint new_value own table_name format a20 head ing 'object|name' trunc column_name format a20 heading 'column|name' trunc privi lege format a9 heading 'privilege' trunc grantee format a17 heading 'user/role t o whom|access is granted' trunc grantor format a10 heading 'user who|made grant' trunc ttitle center 'object owner: 'own skip 2 break on owner skip page on grantee on grantor skip 1 select owner, grantee, grantor, table_name, column_name, privileg e from dba_col_privs order by owner, grantee, grantor, table_name / spool off; ################################################################################ ## ########### --- %purpose: show table structure (column-name, datentyp, etc) f or all schemaowners --########################################################## ######################## ########### -spool show_table_columns.lst set feed off set pagesize 10000 ttitle off -column table_name noprint new_value tab column ow ner format a10 heading 'table|owner' column column_name format a30 heading 'colu mn|name' column data_type format a9 heading 'data|type' column nullable format a 8 heading 'nulls ?'

column data_length format a14 heading 'maximum data|length [bytes]' column data_ precision format a9 heading 'data|precision' column data_scale format a5 heading 'data|scale' -ttitle center 'columns of table: 'tab skip 2 -break on table_name skip page on owner skip 2 -select owner, table_name, column_name, data_type, to _char(data_length) data_length, to_char(data_precision) data_precision, to_char( data_scale) data_scale, decode(nullable,'y','','n','not null') nullable from dba _tab_columns where table_name like upper('%') and upper(owner) not in ('system', 'sys','dbsnmp') order by owner, table_name, column_name; -spool off; -########## ######################################################################## ####### #### --- %purpose: show table structure (column-name, datentyp, etc) for all sch emaowners --#################################################################### ############## ########### -spool show_table_columns.lst set feed off set pagesi ze 10000 ttitle off -column table_name noprint new_value tab column owner format a10 heading 'table|owner' column column_name format a30 heading 'column|name' c olumn data_type format a9 heading 'data|type' column nullable format a8 heading 'nulls ?' column data_length format a14 heading 'maximum data|length [bytes]' co lumn data_precision format a9 heading 'data|precision' column data_scale format a5 heading 'data|scale' -ttitle center 'columns of table: 'tab skip 2 -break on table_name skip page on owner skip 2 -select owner, table_name, column_name,

data_type, to_char(data_length) data_length, to_char(data_precision) data_precis ion, to_char(data_scale) data_scale, decode(nullable,'y','','n','not null') null able from dba_tab_columns where table_name like upper('%') and upper(owner) not in ('system','sys','dbsnmp') order by owner, table_name, column_name; -spool off ; -############################################################################# ##### ########### --- %purpose: show table and column comments --- use: needs or acle dba access --############################################################## #################### ########### -set feed off; set pagesize 10000; set wrap off ; set linesize 200; set heading on; set tab on; set scan on; set verify off; tti tle column column column ttitle off; owner format a5 heading 'table|owner' t1 fo rmat a20 heading 'table|name' comments format a100 heading 'comments' left 'tabl e comments' skip 2 accept user_namen char prompt 'enter schema owner: ' break on owner spool show_t ab_col_comments.lst select owner,table_name t1,comments from dba_tab_comments wh ere owner like upper('&user_namen'); column t2 noprint new_value tab column colu mn_name format a20 heading 'column|name' ttitle off; clear break; ttitle left 'c olumn comments on tabelle: 'tab skip 2 break on t2 skip page on owner skip 2 -

select owner,table_name t2,column_name,comments from dba_col_comments where owne r like upper('&user_namen'); spool off; set feed on echo off termout on pages 24 verify on; ttitle off; -####################################################### ########################### ########### --- %purpose: show tablespace status inf ormation --##################################################################### ############# ########### -ttitle left 'output generated by: ' sql.user ' at: ' format a8 datum skip skip left 'tablespace status' skip left 'oracle version ' f ormat a15 sql.release skip 2 set feed off set pagesize 10000 column datum new_va lue datum noprint column tablespace_name format a64 heading 'tablespace' column status format a15 heading "status" select to_char(sysdate, 'mm/dd/yy') datum, ta blespace_name, status from sys.dba_tablespaces; -############################### ################################################### ########### --- %purpose: sh ow users with high cpu processing since instance startup --##################### ############################################################# ########### -set f eed off; set pagesize 10000; set wrap off; set linesize 80; set heading on; set tab on; set scan on; set verify off; -spool show_users_with_high_cpu_processing. lst ttitle 'show users with high cpu processing' skip 2

column user_process format a10 heading "userprocess(sid)" column value format 99 9,999,999.99 select ss.username||'('||se.sid||')' user_process, value from v$ses sion ss, v$sesstat se, v$statname sn where se.statistic# = sn.statistic# and nam e like '%cpu used by this session%' and se.sid = ss.sid and ss.username is not n ull order by substr(name,1,25), value desc / spool off; set feed on echo off ter mout on pages 24 verify on ttitle off -######################################### ######################################### ########### --- %purpose: show views f or schmea-owner --############################################################## #################### ########### -spool show_views.lst ttitle left 'all database views' skip 2 set feed off set pagesize 30000 set linesize 200 break on owner s kip 1 column owner format a5 heading 'view|owner' column view_name format a20 he ading 'view|name' column text_length format 9999999 heading 'view-length|[bytes] ' select substr(owner,1,5) owner, substr(view_name,1,60) view_name, text_length from dba_views where owner not in ('sys','dbsnmp','system') order by 1,2,3; spoo l off; -######################################################################## ########## ########### --- %purpose: show all invald objects in the database for all users except sys and system --- use: system, sys or user having select any table system privilege --####################################################### ########################### ########### -set verify off

set pagesize 200 set feedback off column owner format a15 column object_name for mat a30 heading 'object' column object_id format 999999 heading "id#" column obj ect_type format a15 column status format a8 ttitle left 'invalid objects found f or ...'skip 2 --- lists all invalid objects for a database -spool list_invalid_o bjects.lst set termout off -select owner, object_name, object_id, object_type, s tatus from dba_objects where status != 'valid' and owner not in ('sys','system') ; -spool off --- create script which can be used to recompile -- all of the inva lid objects -ttitle off set concat + spool compile_invalid_objects.sql set conca t . set feedback off set heading off set pagesize 999 set verify off select dist inct 'sqlplus '||owner||'/'||owner||'<<eof'||chr(10)|| 'prompt compiling '||owne r||' objects...'||chr(10)|| 'execute dbms_utility.compile_schema('||chr(39)||own er||chr(39)||');'|| chr(10)||'show err;'||chr(10)||'quit'||chr(10)||'eof' from d ba_objects where status != 'valid' and object_type != 'view' and owner not in (' sys','system'); select 'sqlplus '||owner||'/'||owner||'<<eof'||chr(10)|| 'prompt compiling '||owner||' views...'||chr(10)|| 'alter view '||object_name||' compil e;'||chr(10)|| 'show errors view '||object_name||';'||chr(10)||'quit'||chr(10)|| 'eof' from dba_objects where status != 'valid' and object_type = 'view' and owne r not in ('sys','system'); spool off set termout on prompt prompt list_invalid_o bjects.lst has been spooled prompt compile_invalid_objects.sql has been spooled prompt

-############################################################################### ### ########### --- %purpose: show all privileges for a connected user through r oles and direct --show all privileges for a connected user over roles and -direc t. show all system- and object privileges as well. --########################### ####################################################### ########### -set feed of f set pagesize 30000 set linesize 200 clear breaks columns set pause off spool s how_privileges_for_user.lis -ttitle left "currently active role(s) for user: " s ql.user skip 2 column username format a22 heading 'user' trunc column role forma t a40 heading 'active|role' trunc column default_role format a7 heading 'default |role' trunc column admin_option format a7 heading 'admin|option' trunc -break o n username select username,role,default_role,admin_option from user_role_privs, session_roles where granted_role = role order by role / -ttitle left "currently inactive role(s) for user: " sql.user skip 2 column username format a22 heading 'user' trunc column granted_role format a40 heading 'granted|role' trunc column default_role format a7 heading 'default|role' trunc column admin_option format a 7 heading 'admin|option' trunc select username,granted_role,default_role,admin_o ption from user_role_privs where not exists (select 'x' from session_roles where role = granted_role) union select 'all role(s) are active','','','' from dual w here 0 = (select count('x') from user_role_privs where not exists (select 'x' fr om session_roles where role = granted_role)) order by 1,2 / --

ttitle left "sub-role(s) for user: " sql.user skip 2 column granted_role format a39 heading 'these role(s) are granted to ...' trunc column role format a39 head ing '... these role(s)' select granted_role,role from role_role_privs union sele ct 'no sub-role(s) found','' from dual where 0 = (select count('x') from role_ro le_privs) / -ttitle "system privileges through roles and direct for user: " sql. user skip 2 column role format a40 heading 'role' trunc column privilege format a30 heading 'system|privilege' trunc column admin_option format a7 heading 'admi n|option' trunc -break on role skip 1 select role,privilege,admin_option from ro le_sys_privs union select 'directly' role,privilege,admin_option from user_sys_p rivs order by 1,2 / -ttitle "object privileges through roles and direct for user : " sql.user skip 2 column role format a20 heading 'role' trunc column owner for mat a17 heading 'object|owner' trunc column table_name format a20 heading 'objec t|name' trunc column privilege format a12 heading 'privilege' trunc column grant able format a6 heading 'admin|option' trunc break on role on owner on table_name select role, owner, table_name, privilege, grantable from role_tab_privs where role in (select role from session_roles) and column_name is null union select 'd irectly' role, owner, table_name, privilege, grantable from user_tab_privs_recd order by 1,2,3,4 / -ttitle "column privileges for user: " sql.user skip 2 column role format a16 heading 'role' trunc column owner format a10 heading 'object|ow ner' trunc column table_name format a20 heading 'object|name' trunc column colum n_name format a20 heading 'column|name' trunc column privilege format a10 headin g 'privilege' trunc

select role, owner, table_name, column_name, privilege, grantable from role_tab_ privs where role in (select role from session_roles) and column_name is not null union select 'directly' role, owner, table_name, column_name, privilege, granta ble from user_col_privs_recd order by 1,2,3,4 / spool off clear breaks columns t title off prompt prompt listing created in "showpriv.lis" prompt -############## #################################################################### ########### --- %purpose: show complete system statistic, e.g. full table scans, redolog in fos from v$sysstat --########################################################### ####################### ########### --- system statistics --- das diagramm system stats zeigt alle parameter der wichtigen system -- statistiktabelle v$sysstat. -- auswertung der system statistik --- aus den systemstatistiken k nnen wichtige i nformationen gewonnen werden. -- man beachte dass es sich bei diesen angaben imm er um kumulierte werte seit -- dem letzten startup handelt. --- full table scans --- table scan blocks gotten 61'900'307 -- table scan rows gotten 194'6840'695 -- table scans (long tables) 13'267 -- table scans (short tables) 307'195 --- in dex scans --- table fetch by rowid 15'653'655 --- redo waits --- redo log space requests 1018 -- redo log space wait time 21263 --- bei gr sseren waits sind die r do-files zu vergr ssern und er parameter -- log_buffer muss erh ht werden. die zeit ist in 1/100 sekunden angegeben -- (21263 = 212 sekunden = 3,5 minuten in etwa 5 wochen).

--############################################################################## #### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 2 00; set heading on; set tab on; set scan on; set verify off; -ttitle left 'syste m statistics' skip 2 select s.name, s.value from v$sysstat s order by s.name, s. value; -######################################################################## ########## ########### --- %purpose: show all schmea objects (tables,synonyms,vi ews,sequences,indexes) --- use: jeder oracle user --############################ ###################################################### ########### -spool show_a ll_objects.lst set feed off set pagesize 10000 ttitle off column column column c olumn column column datum new_value datum noprint owner format a10 heading 'owne r' object_name format a38 heading 'object-|name' object_type format a10 heading 'object-|type' created format a10 heading 'created' status format a8 heading 'st atus' ttitle left 'show all schema objects (tables,synonyms,views,sequences,indexes)' skip 2 break on owner skip 1 on object_type select to_char(sysdate, 'mm/dd/yy') datum, substr(owner,1,10) owner, substr(object_type,1,10) object_type, substr(ob ject_name,1,38) object_name, substr(created,1,11) created, substr(status,1,8) st atus from dba_objects where substr(owner,1,10) not in ('sys','system','public',' dbsnmp') order by 1,2,3,4;

spool off; exit; -############################################################## #################### ########### --- %purpose: show block chaining (chained rows ) with analyze table list chained rows --- use: needs oracle dba access --###### ############################################################################ ### ######## -set echo off termout off drop table lst_chained_rows$tmp; set termout on create table lst_chained_rows$tmp ( owner_name varchar2(30), table_name varch ar2(30), cluster_name varchar2(30), head_rowid rowid, timestamp date ); -accept user_namen char prompt 'username or %: ' accept tabellen_namen char prompt 'tabl ename or %: ' set feed off echo off termout off pages 0 verify off array 1 -spoo l list_chained_rows.sql select 'analyze table '||owner||'.'||table_name, 'list c hained rows into lst_chained_rows$tmp;' from sys.dba_tables where owner like upp er('&user_namen') and table_name like upper('&tabellen_namen') order by owner, t able_name; -spool off set feed on echo on termout on pages 66 verify on @list_ch ained_rows.sql -set echo off column table_name format a30 column owner_name form at a16 trunc -spool list_chained_rows.lst -select rpad(owner_name,16,'.') owner_ name, rpad(c.table_name,30,'.') table_name, num_rows, count(*) ch_rows, pct_free from sys.dba_tables t, lst_chained_rows$tmp c where t.owner = c.owner_name and t.table_name = c.table_name group by owner_name, c.table_name, pct_free, num_row s

union select 'no block chaining',null,0,0,0 from dual where 0 = ( select count(* ) from lst_chained_rows$tmp where rownum = 1 ) order by 1,2; spool off set feed on echo off termout on pages 24 verify on ttitle off drop table lst_chained_rows $tmp; -######################################################################### ######### ########### --- %purpose: show columns that have the same name but dif ferent characteristics --this script lists columns that have the same name but different characteristics. they may cause problems -when tables are joined on th e columns or unexpected -results are returned. --############################### ################################################### ########### -accept user_nam en char prompt 'schemaowner or wildcard : ' set feed off echo off termout on pag es 5000 lines 500 verify off array 1 -spool list_colnames_with_diff_length.lst t title left 'columns with inconsistent data lengths' skip 2 select substr(owner,1 ,10) "owner", column_name "colname", table_name||' '||data_type||'('|| decode(da ta_type, 'number', data_precision, data_length)||')' "characteristics" from all_ tab_columns where (column_name, owner) in (select column_name, owner from all_ta b_columns group by column_name, owner having min(decode(data_type, 'number', dat a_precision, data_length)) < max(decode(data_type, 'number', data_precision, dat a_length))) and owner like upper('&user_namen'); spool off; set feed on echo off termout on pages 24 verify on; -############################################### ################################### ########### --- %purpose: show detailled rep ort of library cache usage in the shared pool of the instance --################ ################################################################## ########### -

-- das diagramm library cache details zeigt detailinformationen -- des library cac he im shared pool der instance. der library cache -- enth lt sql und pl/sql code i n geparster form. es ist wichtig, dass -- die ratio f r diese bereiche nahezu 100% betr gt. --###################################################################### ############ ########### -set feed off; set pagesize 10000; set wrap off; set li nesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle lef t 'library cache details' skip 2 select namespace,gets,gethits, round(gethitrati o*100) "ratio%", pins,pinhits,round(pinhitratio*100) "ratio%" from v$librarycach e order by namespace; -######################################################### ######################### ########### --- %purpose: show fragmented objects (mor e than 3 extents) --- use: needs oracle dba access --########################### ####################################################### ########### -set feed of f set pagesize 5000 break on owner skip 1 on tablespace_name on segment_type col umn datum new_value datum noprint column owner format a10 heading 'owner' column tablespace_name format a20 heading 'tablespace' column segment_type format a10 heading 'segment-|type' column segment_name format a30 heading 'segment-|name' c olumn extent_id format 999 heading 'number of|extents' column bytes format 999,9 99,999,999 heading 'size|[bytes]' --- looking for fragmented objects -select to_ char(sysdate, 'mm/dd/yy') datum, owner, tablespace_name, segment_type, segment_n ame, count(extent_id) extent_id, sum(bytes) bytes

from sys.dba_extents where substr(owner,1,10) not in ('sys') group by owner, tab lespace_name, segment_type, segment_name having count(extent_id) > 3 order by 1, 2,3,4; -######################################################################## ########## ########### --- %purpose: show free space in all datafiles and if aut oextent is on --################################################################ ################## ########### -clear columns breaks computes set pagesize 100 c olumn column column column column column select file_name format a32 tablespace_ name format a15 status format a3 trunc t format 999,999.000 heading "total mb" a format a4 heading "aext" p format 990.00 heading "% free" df.file_name, df.tablespace_name, df. status, (df.bytes/1024000) t, (fs.s/df.byt es*100) p, decode (ae.y,1,'yes','no') a from dba_data_files df, (select file_id, sum(bytes) s from dba_free_space group by file_id) fs, (select file#, 1 y from s ys.filext$ group by file#) ae where df.file_id = fs.file_id and ae.file#(+) = df .file_id order by df.tablespace_name, df.file_id; column file_name clear column tablespace_name clear column status clear column t clear column a clear column p clear ttitle off -############################################################# ##################### ###########

--- %purpose: show information about your current database account (who am i) -################################################################################ ## ########### -set termout off set head off set termout on select 'user: '|| us er || ' on database ' || global_name, '(terminal='||userenv('terminal')|| ', ses sion-id='||userenv('sessionid')||')' from global_name; set head on feed on -#### ############################################################################## # ########## --- %purpose: show installed database version and options with port s pecific infos --- use: needs oracle dba access --############################### ################################################### ########### -set feed off; s et pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; s et scan on; set verify off; set termout on; set serveroutput on; ttitle left 'or acle version:' skip 2 select banner from sys.v$version; ttitle left 'installed o ptions:' skip 2 select parameter from sys.v$option where value = 'true'; ttitle left 'not installed options:' skip 2 select parameter from sys.v$option where va lue <> 'true'; prompt

begin dbms_output.put_line('specific port information: '||dbms_utility.port_stri ng); end; / prompt set head on feed on -######################################## ########################################## ########### --- %purpose: show last c heckpoints in the file headers --############################################### ################################### ########### -ttitle left 'output generated b y: ' sql.user ' at: ' format a8 datum skip skip left 'show last checkpoints in t he file headers' skip left 'oracle version ' format a15 sql.release skip 2 set f eed off set pagesize 10000 set linesize 500 break on grantee skip 1 column datum new_value datum noprint column file_nr format 999999 heading 'file#' column che ckpoint_time format a20 heading 'checkpoint|time' column file_name format a59 he ading 'filename' select file# file_nr, to_char(checkpoint_time,'dd.mm.yyyy:hh24: mi:ss') checkpoint_time, name file_name from v$datafile_header; -############### ################################################################### ########### --- %purpose: show next sequence number from sequence (without to increment it w ith nextval) --- use: needs sys access --####################################### ########################################### ########### -set feed off; set pages ize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on;

set verify off; -spool show_nextval.lst ttitle left 'shows next sequence number without incrementing it' skip 2 -accept sequence_owner char prompt "sequence own er <% for all>: " default % accept sequence_name char prompt "sequence name <% f or all>: " default % -col sequence_owner format a20 heading 'sequence|owner' col sequence_name format a25 heading 'sequence|name' col next_seq format 99999999 h eading 'next|value' col cache format a25 heading 'cache' select sequence_owner, sequence_name, next_seq, cache from (select sequence_owner, sequence_name, nextv alue next_seq, 'in cache' cache from v$_sequences where nextvalue is not null un ion select sequence_owner, sequence_name, highwater next_seq, 'created nocache' cache from v$_sequences where nextvalue is null union select sequence_owner, seq uence_name, last_number next_seq, 'not in cache' cache from dba_sequences s wher e not exists (select sequence_owner, sequence_name from v$_sequences v where v.s equence_name = s.sequence_name and v.sequence_owner = s.sequence_owner)) where s equence_owner like upper('&sequence_owner') and sequence_name like upper('&seque nce_name') order by sequence_owner, sequence_name / undefine sequence_owner unde fine sequence_name col sequence_owner clear col sequence_name clear set verify o n spool off rem -----------------------------------------------------------------------rem shows actual dml-locks (incl. table-name) rem wait = yes are users w aiting for a lock rem ---------------------------------------------------------------------rem -set pages 24 lines 80 feed on echo off termout on head on colum n program format a80 trunc column locker format a10 trunc column t_owner format a10 trunc column object_name format a25 trunc column wait format a4 ttitle "actu al dml-locks (tm+tx)" -select /*+ rule */ decode(l.request,0,'no','yes') wait,

s.osuser, s.process, s.username locker, u.name t_owner, o.name object_name, ' '| |s.program program from v$lock l, v$session s, obj$ o, user$ u where u.user# = o .owner# and s.sid = l.sid and l.id1 = o.obj# and l.type = 'tm' union select deco de(l.request,0,'no','yes') wait, s.osuser, s.process, s.username locker, '-', 'r ecord(s)', ' '||s.program program from v$lock l, v$session s where s.sid = l.sid and l.type = 'tx' order by 7,5,1,2,6 / ttitle off col program clear col locker clear col t_owner clear col object_name clear col wait clear rem -----------------------------------------------------------------------rem show users waiting for a lock, the locker and the rem sql-command they are waiting for a lock rem o suser, schema and pids are shown rem ---------------------------------------------------------------------rem -set pages 24 lines 100 feed on echo off termout on head on column os_locker format a15 trunc column os_waiter format a15 trunc c olumn locker_schema format a15 trunc column waiter_schema format a15 trunc colum n waiter_pid format a10 column locker_pid format a10 column sql_text_waiter form at a100 wrap column database noprint new_value database column datum_zeit noprin t new_value datum_zeit set termout off echo off feed off set termout on ttitle c enter 'current lock-waits' skip 2 -select /*+ ordered no_merge(l_waiter) no_merg e(l_locker) use_hash(l_locker)

*/ no_merge(s_waiter) use_hash(s_waiter) no_merge(s_locker) use_hash(s_locker) use_ nl(o) use_nl(u) /* first the table-level locks (tm) and mixed tm/tx tx/tm */ s_locker.osuser os_ locker, s_locker.username locker_schema, s_locker.process locker_pid, s_waiter.o suser os_waiter, s_waiter.username waiter_schema, s_waiter.process waiter_pid, ' table lock (tm): '||u.name||'.'||o.name|| ' - mode held: '|| decode(l_locker.lmo de, 0, 'none', /* same as monitor */ 1, 'null', /* n */ 2, 'row-s (ss)', /* l */ 3, 'row-x (sx)', /* r */ 4, 'share', /* s */ 5, 's/row-x (ssx)', /* c */ 6, 'ex clusive', /* x */ '???: '||to_char(l_locker.lmode))|| ' / mode requested: '|| de code(l_waiter.request, 0, 'none', /* same as monitor */ 1, 'null', /* n */ 2, 'r ow-s (ss)', /* l */ 3, 'row-x (sx)', /* r */ 4, 'share', /* s */ 5, 's/row-x (ss x)', /* c */ 6, 'exclusive', /* x */ '???: '||to_char(l_waiter.request)) sql_tex t_waiter from v$lock l_waiter, v$lock l_locker, v$session s_waiter, v$session s_ locker, obj$ o, user$ u where s_waiter.sid = l_waiter.sid and l_waiter.type in ( 'tm') and s_locker.sid = l_locker.sid and l_locker.id1 = l_waiter.id1 and l_wait er.request > 0 and l_locker.lmode > 0 and l_waiter.addr != l_locker.addr and l_w aiter.id1 = o.obj# and u.user# = o.owner# union select /*+ ordered no_merge(l_wa iter) no_merge(l_locker) use_hash(l_locker) no_merge(s_waiter) use_hash(s_waiter ) no_merge(s_locker) use_hash(s_locker) no_merge(l1_waiter) use_hash(l1_waiter) no_merge(o) use_hash(o)

*/ /* now the (usual) row-locks tx */ s_locker.osuser os_locker, s_locker.userna me locker_schema, s_locker.process lock_pid, s_waiter.osuser os_waiter, s_waiter .username waiter_schema, s_waiter.process waiter_pid, 'tx: '||o.sql_text sql_tex t_waiter from v$lock l_waiter, v$lock l_locker, v$session s_waiter, v$session s_ locker, v$_lock1 l1_waiter, v$open_cursor o where s_waiter.sid = l_waiter.sid an d l_waiter.type in ('tx') and s_locker.sid = l_locker.sid and l_locker.id1 = l_w aiter.id1 and l_waiter.request > 0 and l_locker.lmode > 0 and l_waiter.addr != l _locker.addr and l1_waiter.laddr = l_waiter.addr and l1_waiter.kaddr = l_waiter. kaddr and l1_waiter.saddr = o.saddr and o.hash_value = s_waiter.sql_hash_value / ttitle off column os_locker clear column os_waiter clear column locker_schema c lear column waiter_schema clear column waiter_pid clear column locker_pid clear column sql_text_waiter clear column database clear column datum_zeit clear rem r em $header: utllockt.sql 21-jan-2003.16:21:56 bnnguyen exp $ locktree.sql rem re m copyright (c) 1989, 2003, oracle corporation. all rights reserved. rem name re m utllockt.sql rem function - print out the lock wait-for graph in tree structur ed fashion. rem this is useful for diagnosing systems that are hung on locks. re m notes rem modified rem bnnguyen 01/21/03 - bug2166717 rem pgreenwa 04/27/95 fix column definitions for lock_holders rem pgreenwa 04/26/95 - modify lock_hold ers query to use new dba_locks f rem glumpkin 10/20/92 - renamed from locktree.s ql rem jloaiza 05/24/91 - update for v7 rem rlim 04/29/91 - change char to varch ar2 rem loaiza 11/01/89 - creation rem /* print out the lock wait-for graph in a tree structured fashion.

* * this script prints the sessions in the system that are waiting for * locks, and the locks that they are waiting for. the printout is tree * structured. if a sessionid is printed immediately below and to the right * of another session, t hen it is waiting for that session. the session ids * printed at the left hand s ide of the page are the ones that everyone is * waiting for. * * for example, in the following printout session 9 is waiting for * session 8, 7 is waiting for 9 , and 10 is waiting for 9. * * waiting_session type mode requested mode held loc k id1 lock id2 * ----------------- ---- ----------------- ----------------- ------- -------* 8 none none none 0 0 * 9 tx share (s) exclusive (x) 65547 16 * 7 r w exclusive (x) s/row-x (ssx) 33554440 2 * 10 rw exclusive (x) s/row-x (ssx) 335 54440 2 * * the lock information to the right of the session id describes the lo ck * that the session is waiting for (not the lock it is holding). * * note that this is a script and not a set of view definitions because * connect-by is used in the implementation and therefore a temporary table * is created and dropped since you cannot do a join in a connect-by. * * this script has two small disadv antages. one, a table is created when * this script is run. to create a table a number of locks must be * acquired. this might cause the session running the scr ipt to get caught * in the lock problem it is trying to diagnose. two, if a sess ion waits on * a lock held by more than one session (share lock) then the wait-f or graph * is no longer a tree and the conenct-by will show the session (and any * sessions waiting on it) several times. */ /* select all sids waiting for a lo ck, the lock they are waiting on, and the * sid of the session that holds the lo ck. * union * the sids of all session holding locks that someone is waiting on t hat * are not themselves waiting for locks. these are included so that the roots * of the wait for graph (the sessions holding things up) will be displayed. */ drop table lock_holders; create table lock_holders /* temporary table */ ( waiti ng_session number, holding_session number, lock_type varchar2(26), mode_held var char2(14), mode_requested varchar2(14), lock_id1 varchar2(22), lock_id2 varchar2 (22) ); drop table dba_locks_temp; create table dba_locks_temp as select * from dba_locks;

/* this is essentially a copy of the dba_waiters view but runs faster since * it caches the result of selecting from dba_locks. */ insert into lock_holders sele ct w.session_id, h.session_id, w.lock_type, h.mode_held, w.mode_requested, w.loc k_id1, w.lock_id2 from dba_locks_temp w, dba_locks_temp h where h.blocking_other s = 'blocking' and h.mode_held != 'none' and h.mode_held != 'null' and w.mode_re quested != 'none' and w.lock_type = h.lock_type and w.lock_id1 = h.lock_id1 and w.lock_id2 = h.lock_id2; commit; drop table dba_locks_temp; insert into lock_hol ders select holding_session, null, 'none', null, null, null, null from lock_hold ers minus select waiting_session, null, 'none', null, null, null, null from lock _holders; commit; column column column column waiting_session format a17; lock_t ype format a17; lock_id1 format a17; lock_id2 format a17; /* print out the result in a tree structured fashion */ select lpad(' ',3*(level -1)) || waiting_session waiting_session, lock_type, mode_requested, mode_held, l ock_id1, lock_id2 from lock_holders connect by prior waiting_session = holding_s ession start with holding_session is null; drop table lock_holders; -########### ####################################################################### ######## ### --- %purpose: show the most resource intensive sql statements that have been recently executed --- displays a list of the most resource intensive sql statem ents -- that have been recently executed. resource use is ranked by the

-- number of sga buffer gets, which is a good indicator of the work done. -- onl y statements that are still cached in the sga are searched -- statements are dis carded using an lru algorithim. --############################################## #################################### ########### -set linesize 1200 verify off f eedback 100 accept gets default 100000 prompt "min buffer gets [100,000] " col s ql_text for a1000 select s.buffer_gets, s.disk_reads, s.rows_processed, s.execut ions, substr(u.name,1,10) username, s.sql_text from v$sqlarea s, sys.user$ u whe re s.buffer_gets > &&gets and s.parsing_user_id = u.user# and u.name <> 'sys' or der by s.buffer_gets desc / set feedback on -################################### ############################################### ########### --- %purpose: show t he most resource intensive sql statements that have been recently executed --- d isplays a list of the most resource intensive sql statements -- that have been r ecently executed. resource use is ranked by the -- number of sga buffer gets, wh ich is a good indicator of the work done. -- only statements that are still cach ed in the sga are searched -- statements are discarded using an lru algorithim. --############################################################################## #### ########### -set linesize 1200 verify off feedback 100 accept gets default 100000 prompt "min buffer gets [100,000] " col sql_text for a1000 select s.buffe r_gets, s.disk_reads,

from s.rows_processed, s.executions, substr(u.name,1,10) username, s.sql_text v$sqlarea s, sys.user$ u where s.buffer_gets > &&gets and s.parsing_user_id = u. user# and u.name <> 'sys' order by s.buffer_gets desc / set feedback on -####### ########################################################################### #### ####### --- %purpose: show total, free and used space in all tablespaces / datab ase files --- use: needs oracle dba access --################################### ############################################### ########### -clear buffer clear columns clear breaks set linesize 500 set pagesize 5000 column a1 heading 'table space' format a15 column a2 heading 'data file' format a45 column a3 heading 'to tal|space [mb]' format 99999.99 column a4 heading 'free|space [mb]' format 99999 .99 column a5 heading 'free|%' format 9999.99 break on a1 on report compute sum of a3 on a1 compute sum of a4 on a1 compute sum of a3 on report compute sum of a 4 on report select a.tablespace_name a1, a.file_name a2, a.avail a3, nvl(b.free, 0) a4, nvl(round(((free/avail)*100),2),0) a5 from (select tablespace_name, subst r(file_name,1,45) file_name, file_id, round(sum(bytes/(1024*1024)),3) avail from sys.dba_data_files group by tablespace_name, substr(file_name,1,45), file_id) a , (select tablespace_name, file_id, round(sum(bytes/(1024*1024)),3) free

from sys.dba_free_space group by tablespace_name, file_id) b where a.file_id = b .file_id (+) order by 1, 2 / -################################################## ################################ ########### --- %purpose: show waiting sessions blocked through other sessions --############################################## #################################### ########### --- die view row_lock_waits zei gt die wartenden sessions. dieses statement -- ist als view implementiert, es da rf keine rows zur ckbringen, da sonst -- ein user warten muss. --- create or repla ce view row_lock_waits -- (username, sid, object_owner, -- object_name, sql_text , file_nr, block_nr, record_nr) -- as -- select s.username, s.sid, -- o.owner, - o.object_name, -- a.sql_text, -- s.row_wait_file#, -- s.row_wait_block#, -- s. row_wait_row# -- from v$session s, v$sqlarea a, dba_objects o -- where o.object_ id = s.row_wait_obj# -- and s.sql_address = a.address -- and s.row_wait_obj# > 0 ; --############################################################################ ###### ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -ttitle left 'wai ting sessions' skip 2 select * from row_lock_waits; -########################### ####################################################### ########### --- %purpose : show which users are accessing which rollback segments. --

-it is sometimes useful to know which users are accessing the rollback segments. -this is important when a user is continally filling the rollback segments --## ################################################################################ ########### -set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set verify off; -spool show_rollback_se gment_usage.lst ttitle 'current rollback segment usage' skip 2 column "rollback segment name" format a18; column "oracle user session" format a40; select r.name "rollback segment name", p.spid "process id", s.username||'('||l.sid||')' "orac le user session", sq.sql_text from v$sqlarea sq, v$lock l, v$process p, v$sessio n s, v$rollname r where l.sid = p.pid(+) and s.sid = l.sid and trunc(l.id1(+) / 65536) = r.usn and l.type(+) = 'tx' and l.lmode(+) = 6 and s.sql_address = sq.ad dress and s.sql_hash_value = sq.hash_value order by r.name / spool off; set feed on echo off termout on pages 24 verify on ttitle off -######################### ######################################################### ########### --- %purpo se: show which users are accessing which rollback segments. --it is sometimes us eful to know which users are accessing the rollback segments. -this is important when a user is continally filling the rollback segments --##################### ############################################################# ########### --

set feed off; set pagesize 10000; set wrap off; set linesize 200; set heading on ; set tab on; set scan on; set verify off; -spool show_rollback_segment_usage.ls t ttitle 'current rollback segment usage' skip 2 column "rollback segment name" format a18; column "oracle user session" format a40; select r.name "rollback seg ment name", p.spid "process id", s.username||'('||l.sid||')' "oracle user sessio n", sq.sql_text from v$sqlarea sq, v$lock l, v$process p, v$session s, v$rollnam e r where l.sid = p.pid(+) and s.sid = l.sid and trunc(l.id1(+) / 65536) = r.usn and l.type(+) = 'tx' and l.lmode(+) = 6 and s.sql_address = sq.address and s.sq l_hash_value = sq.hash_value order by r.name / spool off; set feed on echo off t ermout on pages 24 verify on ttitle off -####################################### ########################################### ########### --- %purpose: show sid,s erial#,pid,status,schema,osuser,box,prg,logon_time of logged on users --######## ########################################################################## ##### ###### -set linesize 200 pagesize 1000 feed off; column "sid,serial#" format a12 column "pid" format 999 column "status" format a8 column "schema" format a10 co lumn "osuser" format a10 column "box" format a16 column "prg" format a30 -select '''' || s.sid || ','

v$session s, v$process p where s.paddr = p.addr order by s.username / -######### ######################################################################### ###### ##### --- %purpose: shows sql-statement for connected sid/srl# from v$sqltext -################################################################################ ## ########### -set linesize 2000 trimspool on select to_char(s.sid,'999') sid, to_char(s.serial#,'999999') srl#, substr(s.osuser,1,10) osusr, substr(s.schemana me,1,10) schema, substr(t.sql_text,1,100) sql_text from v$session s, v$sqltext t where s.type <> 'background' and s.sql_address = t.address (+) and t.piece (+) = 0 order by s.status, s.sid / -################################################ ################################## ########### --- %purpose: shows the user that has performed the most physical disk reads --- this script shows the user that has performed the most physical -- disk reads. you use the columns sid and seria l# as input into -- dbms_system.set_sql_trace_in_session to commence tracing the -- offending user. --########################################################## ######################## ########### || || , , , , , , , from s.serial# ''';' "sid,serial#" p.spid "pid" s.status "status" s.schemaname "schem a" s.osuser "osuser" s.machine "box" s.program "prg" to_char(s.logon_time, 'dd.m m.yyyy hh24:mi') "logon_time"

-select ses.sid, ses.serial#, ses.osuser, ses.process, sio.physical_reads from v $session ses, v$sess_io sio where ses.sid = sio.sid and nvl(ses.username,'sys') not in ('sys', 'system') and sio.physical_reads = (select max(physical_reads) fr om v$session ses2, v$sess_io sio2 where ses2.sid = sio2.sid and ses2.username no t in ('system', 'sys')); -###################################################### ############################ ########### --- %purpose: shows the user that has p erformed the most physical disk reads --- this script shows the user that has pe rformed the most physical -- disk reads. you use the columns sid and serial# as input into -- dbms_system.set_sql_trace_in_session to commence tracing the -- of fending user. --################################################################ ################## ########### -select ses.sid, ses.serial#, ses.osuser, ses.pro cess, sio.physical_reads from v$session ses, v$sess_io sio where ses.sid = sio.s id and nvl(ses.username,'sys') not in ('sys', 'system') and sio.physical_reads = (select max(physical_reads) from v$session ses2, v$sess_io sio2 where ses2.sid = sio2.sid and ses2.username not in ('system', 'sys')); -####################### ########################################################### ########### --- %pur pose: solutions for the "mutation table problem" with delete cascade and cascade update --###################################################################### ############ ########### --- see http://www.akadia.com/services/ora_mutating_tab le_problems.html for the whole text. --- solution: using a temporary table --- i f you need to update a mutating table, then you could use a temporary table, -a pl/sql table, or a package variable to bypass these restrictions. for example, -- in place of a single after row trigger that updates the original table, resu lting in -- a mutating table error, you may be able to use two triggers - an aft er row trigger that -- updates a temporary table, and an after statement trigger that updates the

original table -- with the values from the temporary table. --- in the next exam ple "from the real world", we want to show this. the table cug can -- only have records of the following types --- a: type = 1 -- b: type = 2 (leader for c or d ) -- c: type = 3 (lead by b) -- d: type = 4 (lead by b) -- note, that the types c and d must be lead by the cug type b. -drop table cug cascade constraints; cre ate table cug ( id_cug number(12) not null primary key, id_b number(12) not null , type number(1), foreign key (id_b) references cug (id_cug) on delete cascade); drop table cugtmp; create global temporary table cugtmp ( id_b number(12), type number(1)) on commit delete rows; create or replace trigger bi_r before insert on cug for each row declare l_type cug.type%type; begin if (:new.type in (3,4)) then select type into l_type from cug where id_cug = :new.id_b; end if; if (l_ty pe != 2) then raise_application_error(-20002, 'project- and community cugs must have a leading company'); end if; end; / create or replace trigger au_r after up date of id_b on cug for each row begin insert into cugtmp (id_b,type) values (:n ew.id_b,:new.type); end; / create or replace trigger au_s after update of id_b o n cug declare l_id_b number(12); l_typecd number(1); l_typeb number(1);

cursor cur_cugtmp is select id_b,type from cugtmp; begin open cur_cugtmp; loop f etch cur_cugtmp into l_id_b,l_typecd; exit when cur_cugtmp%notfound; dbms_output .put_line('debug: au_s: id_b ' || to_char(l_id_b) || ', type : ' || to_char(l_ty pecd)); select type into l_typeb from cug where id_cug = l_id_b; dbms_output.put _line('au_s: type : ' || to_char(l_typeb)); if (l_typeb != 2) then raise_applica tion_error(-20002, 'project- and community cugs must have a leading company'); e nd if; end loop; close cur_cugtmp; end; / insert into cug (id_cug,id_b,type) val ues (0,0,0); -- company 1 insert into cug (id_cug,id_b,type) values (1,0,2); -company 2 insert into cug (id_cug,id_b,type) values (2,0,2); -- project 1 insert into cug (id_cug,id_b,type) values (3,1,3); -- project 2 insert into cug (id_cu g,id_b,type) values (4,2,3); -- community 1 insert into cug (id_cug,id_b,type) v alues (5,1,4); -- community 2 insert into cug (id_cug,id_b,type) values (6,2,4); commit; update cug set id_b = 2 where id_cug in (3,4,5,6); -################### ############################################################### ########### --%purpose: summary of invalid objects ordered by object type --- use: needs oracl e dba access --################################################################# ################# ########### -spool show_summary_invalid_objects.lst

set set set set set set set set set pause off feed off; pagesize 10000; wrap off; linesize 200; heading on; tab on; scan on; verify off; ttitle left 'summary of invalid objects for user: ' sql.user skip 2 column objec t_type format a25 wrap heading 'object|type' column status format a8 heading 'st atus' select distinct (object_type), status, count(*) from dba_objects where sta tus != 'valid' group by owner, object_type, status; -########################### ####################################################### ########### --- %purpose : try to set sql_trace on for another session / program --- use: sys-user --#### ############################################################################## # ########## -create or replace procedure try_sql_trace_for_session (progname in v archar2) is --- try to enable sql_trace for progname --- example --- sql> set se rveroutput on; -- sql> execute sys.try_sql_trace_for_session('sqlnav'); -- sid: 11 serial#: 58 -- tracing enabled ... bye, bye --- pl/sql procedure successfully completed. -ncount number := 0; cursor select from where curs_get_sid is sid,se rial# v$session program like '%'||progname||'%'; begin while ncount = 0 loop for rec in curs_get_sid loop dbms_output.put_line('s id: '||rec.sid||' serial#: '||rec.serial#);

end; / -######################################################################## ########## ########### --- %purpose: tuning redologs und checkpoints (contention , waits, number/duration of checkpoints) --##################################### ############################################# ########### 1). redolog buffer con tention ----------------------------select substr(name,1,20) "name",gets,misses, immediate_gets,immediate_misses from v$latch where name in ('redo allocation', ' redo copy'); name gets misses immediate_gets immediate_misses ------------------- ---------- ---------- -------------- ---------------redo allocation 277'446'7 80 2'534'627 0 0 redo copy 33'818 27'694 357'613'861 150'511 misses/gets (must b e < 1%) redo allocation: (2'534'627 / 277'446'780) * 100 = 0.91 % redo copy: (27 '694 / 33'818) * 100 = 81.8 % immediate_misses/(immediate_gets+immediate_misses) (must be < 1%) redo copy: 150'511/(150'511+357'613'861) = 0.04 % 2). waits on r edo log buffer ---------------------------select name,value from v$sysstat where name = 'redo log space requests'; the value of 'redo log space requests' reflec ts the number of times a user process waits for space in the redo log buffer. op timal is if the value is near 0 (oracle manual says this ...) name value --------------------------------------------------------------- ---------redo log spac e requests 22641 4). number of checkpoints per hour --------------------------------set feed off; set pagesize 10000; set wrap off; dbms_system.set_sql_trace_in_session(rec.sid,rec.serial#,true); ncount := 1; end loop; dbms_lock.sleep(10); end loop; dbms_output.put_line('tracing enabled ... bye, bye');

set linesize 200; set heading on; set tab on; set scan on; set verify off; -spoo l show_logswitches.lst ttitle left 'redolog file status from v$log' skip 2 selec t group#, sequence#, members, archived, status, first_time from v$log; ttitle le ft 'number of logswitches per hour' skip 2 select to_char(first_time,'yyyy.mm.dd ') day, to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),' 00' ,1,0)),'99') "00", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh 24:mi'),10,2),'01' ,1,0)),'99') "01", to_char(sum(decode(substr(to_char(first_ti me,'ddmmyyyy:hh24:mi'),10,2),'02' ,1,0)),'99') "02", to_char(sum(decode(substr(t o_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'03' ,1,0)),'99') "03", to_char(sum( decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'04' ,1,0)),'99') "04 ", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'05' , 1,0)),'99') "05", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi '),10,2),'06' ,1,0)),'99') "06", to_char(sum(decode(substr(to_char(first_time,'d dmmyyyy:hh24:mi'),10,2),'07' ,1,0)),'99') "07", to_char(sum(decode(substr(to_cha r(first_time,'ddmmyyyy:hh24:mi'),10,2),'08' ,1,0)),'99') "08", to_char(sum(decod e(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'09' ,1,0)),'99') "09", to _char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'10' ,1,0)) ,'99') "10", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10 ,2),'11' ,1,0)),'99') "11", to_char(sum(decode(substr(to_char(first_time,'ddmmyy yy:hh24:mi'),10,2),'12' ,1,0)),'99') "12", to_char(sum(decode(substr(to_char(fir st_time,'ddmmyyyy:hh24:mi'),10,2),'13' ,1,0)),'99') "13", to_char(sum(decode(sub str(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'14' ,1,0)),'99') "14", to_char (sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'15' ,1,0)),'99' ) "15", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),' 16' ,1,0)),'99') "16", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh 24:mi'),10,2),'17' ,1,0)),'99') "17", to_char(sum(decode(substr(to_char(first_ti me,'ddmmyyyy:hh24:mi'),10,2),'18' ,1,0)),'99') "18", to_char(sum(decode(substr(t o_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'19' ,1,0)),'99') "19", to_char(sum( decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'20'

,1,0)),'99') "20", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:m i'),10,2),'21' ,1,0)),'99') "21", to_char(sum(decode(substr(to_char(first_time,' ddmmyyyy:hh24:mi'),10,2),'22' ,1,0)),'99') "22", to_char(sum(decode(substr(to_ch ar(first_time,'ddmmyyyy:hh24:mi'),10,2),'23' ,1,0)),'99') "23" from v$log_histor y group by to_char(first_time,'yyyy.mm.dd') / spool off; day 00 01 02 03 04 05 0 6 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ----- --- --- --- --- --- -- --- --- --- --- --- --- --- --- --- --- --- --- ----- --- --- --- --07/07 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 0 0 0 0 0 0 0 0 07/08 0 0 0 0 0 0 0 0 0 0 0 5 0 4 1 0 1 0 0 0 0 0 0 0 07/12 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0 07/13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 07/14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 07/15 1 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 1 2 2 0 0 0 0 0 07/16 0 0 10 10 15 11 5 0 0 0 0 0 2 5 5 4 5 7 6 6 7 4 4 4 07/17 2 2 1 3 4 6 9 10 11 1 1 12 12 11 11 12 11 11 12 12 9 9 10 12 9 07/18 12 9 10 10 8 8 9 10 9 8 9 10 10 1 1 10 11 10 10 11 10 11 9 10 10 07/19 9 3 1 1 0 0 4 6 7 7 4 5 11 10 5 4 5 7 6 8 7 5 5 3 07/20 1 1 8 10 7 5 4 5 4 5 7 7 9 7 9 9 7 9 10 11 12 11 12 9 07/21 9 10 10 10 12 10 7 8 9 8 9 10 11 11 11 8 10 10 12 7 6 7 7 7 07/22 8 7 9 10 8 6 7 8 8 8 9 9 9 10 9 9 9 9 9 9 10 7 6 7 07/23 5 5 7 7 7 2 3 3 4 5 6 5 5 4 3 3 4 4 6 6 5 9 8 5 07/24 4 4 5 4 7 6 5 8 8 11 11 11 log_checkpoint_interval = 900'000'000 (ok, must be greather than redolog-file) log_checkpoint_timeout = 1200 (set it to 0, so time-based checkpoints are disabled) 5). time needed to write a checkpoint -----------------------------------beginning database checkpoint by background mo n aug 2 16:37:36 1999 thread 1 advanced to log sequence 2860 current log# 4 seq# 2860 mem# 0: /data/ota/db1/otasicap/redo/redootasicap04.log mon aug 2 16:43:31 1999

completed database checkpoint by background ==> 6 minutes mon aug 2 16:45:15 199 9 beginning database checkpoint by background mon aug 2 16:45:15 1999 thread 1 a dvanced to log sequence 2861 current log# 5 seq# 2861 mem# 0: /data/ota/db1/otas icap/redo/redootasicap05.log mon aug 2 16:50:29 1999 completed database checkpoi nt by background ==> 5.5 minutes mon aug 2 16:51:50 1999 beginning database chec kpoint by background mon aug 2 16:51:51 1999 thread 1 advanced to log sequence 2 862 current log# 6 seq# 2862 mem# 0: /data/ota/db1/otasicap/redo/redootasicap06. log mon aug 2 16:56:44 1999 completed database checkpoint by background ==> 5.5 minutes-######################################################################## ########## ########### --- %purpose: which roles are currently enabled for my se ssion ? --when a user logs on, oracle enables all privileges granted explicitly -to the user and all privileges in the user's default roles. during the -session , the user or an application can use the set role statement -any number of times to change the roles currently enabled for the session. -the number of roles tha t can be concurrently enabled is limited by the -initialization parameter max_en abled_roles. you can see which roles are -currently enabled by examining the ses sion_roles data dictionary view. --############################################# ##################################### ########### -select role from session_role s; --- you can check the db access in your application context using the followi ng code construct. -declare hasaccess boolean := false; cursor cur_get_role is s elect role from session_roles; begin for role_rec in cur_get_role loop if (upper (role_rec.role) in ('admin','clerk')) then

hasaccess := true; end if; end loop; if (not hasaccess) then raise_application_e rror (-20020,'sorry, you have no access to the database'); end if; end; /

You might also like