Oracle Db a Scripts One in All

152
-- ################################################################################## ########### -- -- %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 10000; set wrap off; set linesize 200; set heading on; set tab on; set scan on; set 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','system'); / -- spool off; set feed on; @compute_or_estimate.sql -- ################################################################################## ########### -- -- %purpose: buffer cache analysis - objects (analysis of v$cache) -- -- 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 off; set verify off;

Transcript of Oracle Db a Scripts One in All

Page 1: Oracle Db a Scripts One in All

-- #############################################################################################---- %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 10000;set wrap off;set linesize 200;set heading on;set tab on;set scan on;set 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_tableswhere owner not in ('sys','system');/--spool off;set feed on;@compute_or_estimate.sql

-- #############################################################################################---- %purpose: buffer cache analysis - objects (analysis of v$cache)---- 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 off;set verify off;

Page 2: Oracle Db a Scripts One in All

set termout on;

column bt format a29 heading 'block type'column kind format a12 heading 'object type'column cb format 99990 heading 'nr of blocks'column name format a24 heading 'object name'

ttitle left 'buffer cache analysis - objects' skip 2

spool buffer_cache_analysis_obj.log

select 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 from 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 pagesize 10000;set wrap off;set linesize 200;set heading on;set tab on;set scan on;set verify off;set termout on;

ttitle left 'buffer cache analysis - slot status' skip 2

Page 3: Oracle Db a Scripts One in All

spool buffer_cache_analysis_slots.log

select decode (status, 'free', 'free', 'xcur', 'inst excl', 'scur', 'inst shar', 'cr', 'cons read', 'read', 'disk read', 'mrec', 'med reco', 'irec', 'ins reco', 'other') "slot status", count(*) "counts" from v$cache group by 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,prompt the more trouble the dbwr is having keeping up.promptprompt average length of the dirty buffer write queue:promptprompt if this is larger than the value of:promptprompt 1. (db_files * db_file_simultaneous_writes)/2 [calculation-1]promptprompt orpromptprompt 2. 1/4 of db_block_buffers [calculation-1]promptprompt which ever is smaller and also there is a platform specific limitprompt on the write batch size (normally 1024 or 2048 buffers). if the averageprompt length of the dirty buffer write queue is larger than the valueprompt calculated 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(decode(name,'db_file_simultaneous_writes',value)))/2 "calculation-1"from v$system_parameter

Page 4: Oracle Db a Scripts One in All

where name in ('db_files','db_file_simultaneous_writes');--select (sum(decode(name,'db_block_buffers',value)) / 4) "calculation-2"from v$system_parameterwhere name in ('db_block_buffers');--select sum(decode(name,'summed dirty queue length',value)) / sum(decode(name,'write requests',value)) "write request length" from v$sysstat where name in ( 'summed dirty queue length','write requests') and value > 0;

-- #############################################################################################---- %purpose: circuits trough dispatcher to shared serverprozess, mts und shared-server---- #############################################################################################---- das diagramm circuit zeigt die virtuellen verbindung zur datenbank� �-- instance via dispatcher und shared serverprozess, welcher den user-- process verarbeitet.---- dispatcher statistics---- das diagramm dispatcher zeigt die statistiken der dispatcher prozesse� �-- der datenbank instance.---- actual mts-parameters---- select name, value-- from v$parameter-- where name like '%mts%' or name like '%mts%';---- max. number of server-processes---- 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;

Page 5: Oracle Db a Scripts One in All

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.dispatcher = 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, accept, 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$queuewhere type = 'common';

ttitle left 'activity of mts' -skip 2

select rawtohex(paddr), type, queued, totalq, decode(totalq, 0, 0, wait/totalq/100) "totalq" from v$queue order by paddr;-- #############################################################################################---- %purpose: compare hw-mark which is say 20% larger than the actual data in the tables (ora7)---- this script lists all of the tables specified by owner,-- where the high water mark is say 20% larger than the actual-- data in the 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 not need to run an analyze on the tables before running-- this script---- the rowid format changed between oracle 7 and oracle 8.---- ################################-- this script is for oracle 7 only-- ################################

Page 6: Oracle Db a Scripts One in All

---- author: john dixon, published on http://www.revealnet.com---- #############################################################################################--set echo off set heading off set pagesize 0 set feedback offset linesize 1000set trimspool onset wrap onset verify offrem get the variablesaccept table_owner char prompt 'enter the table owner: 'accept percentage_larger number default 20 prompt 'enter the percentage larger threshold the hwm can be [default 20]: 'prompt this may take a while...rem set termout offrem spool hwm_get_sql.lstprompt set echo off prompt set heading offprompt set termout onprompt set verify off

rem step 1 - first generate the script to calc hwm and data for each table 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.blocks*'||vp.value/1024||'/1024) as hwm '||chr(10)||'from dba_segments s, dba_tables 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 where ds.owner=upper('&&table_owner') andds.segment_name=dt.table_name and ds.owner=dt.owner and vp.name='db_block_size'order by segment_name / spool off

rem step 2 - now generate the output

rem spool hwm.lstset termout oncolumn owner format a10 heading owner column segment_name format a40

Page 7: Oracle Db a Scripts One in All

column hwm format 999,999,999column actual_data format 999,999,999

prompt high water mark report - this will indicate tables that require rebuilding.prompt owner table hwm(mb) data(mb)start hwm_get_sql.lstrem spool off (hwm.lst)

-- #############################################################################################---- %purpose: compare hw-mark which is say 20% larger than the actual data in the tables (ora8)---- this script lists all of the tables specified by owner,-- where the high water mark is say 20% larger than the actual-- data in the 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 not need to run an analyze on the tables before running-- this script---- the rowid format changed between oracle 7 and oracle 8.---- ################################-- this script is for oracle 8 only-- ################################---- author: john dixon, published on http://www.revealnet.com---- #############################################################################################--set echo off set heading off set pagesize 0 set feedback offset linesize 1000set trimspool onset wrap onset verify offrem get the variablesaccept table_owner char prompt 'enter the table owner: 'accept percentage_larger number default 20 prompt 'enter the percentage larger threshold the hwm can be [default 20]: 'prompt this may take a while...rem set termout offrem spool hwm_get_sql.lst

Page 8: Oracle Db a Scripts One in All

prompt set echo off prompt set heading offprompt set termout onprompt set verify off

rem step 1 - first generate the script to calc hwm and data for each table in schema.

select 'select owner,segment_name,hwm,actual_data from'||chr(10)||' (select 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||'/1024) as hwm '||chr(10)||'from dba_segments s, dba_tables 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 where ds.owner=upper('&&table_owner') andds.segment_name=dt.table_name and ds.owner=dt.owner and vp.name='db_block_size'order by segment_name / spool off

rem step 2 - now generate the output

rem spool hwm.lstset termout oncolumn owner format a10 heading owner column segment_name format a40column hwm format 999,999,999column actual_data format 999,999,999

prompt high water mark report - this will indicate tables that require rebuilding.prompt owner table hwm(mb) data(mb)start hwm_get_sql.lstrem 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 to search, oracle returns result,-- if no match is found, oracle returns default.---- #############################################################################################---- quite slow is .......--

Page 9: Oracle Db a Scripts One in All

select count(*), sum(sal)from empwhere deptno = 10and ename like 'smith%';--select count(*), sum(sal)from empwhere deptno = 30and ename like 'smith%';---- .... the same result much more efficiently with decode---- remeber that null values 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(decode(deptno,30,sal,null)) d30_salfrom empwhere ename like 'smith%';

-- #############################################################################################---- %purpose: database trigger to implement an update cascade with oracle8i---- in oracle8i the referential integrity is checked in the-- trigger, therefore there is no mutating problem. however-- there is one problem with the following update:---- update dept set deptno = deptno + 10;---- this update will update all departments with deptno 10-- to the already existing deptno 20, and triggers 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 ... finally 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_updateafter update on scott.deptreferencing new as new old as oldfor each row

declare edeptnoexists exception;

Page 10: Oracle Db a Scripts One in All

-- check if child table have child records with this new -- deptno, this is not allowed.

cursor curs_exists_deptno is select 'x' from emp where deptno = :new.deptno;

rtemp curs_exists_deptno%rowtype;

begin if(:new.deptno <> :old.deptno) then

open curs_exists_deptno; fetch curs_exists_deptno into rtemp;

if (curs_exists_deptno%found) then close curs_exists_deptno; raise edeptnoexists; end if;

close curs_exists_deptno;

update emp set deptno = :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 so on ...');end dept_emp_update;-- #############################################################################################---- %purpose: date arithmetic with oracle (e.g. how to add 1 [sec] to a date ?)---- you can add and subtract number constants as well as other dates-- from dates. oracle interprets number constants 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 from 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 divide date values. oracle provides functions for many common date-- operations. for example, the add_months function lets you add or subtract-- months from a date. the months_between function returns the number of-- months between two dates. the fractional portion of the result represents

Page 11: Oracle Db a Scripts One in All

-- 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.mm.yyyy:hh24:mi:ss'); newdate := olddate + 1/86400; dbms_output.put_line( 'newdate=' ||to_char(newdate,'dd.mm.yyyy:hh24:mi:ss');end;/

newdate=01.01.2000:00:00:00pl/sql procedure successfully completed.-- #############################################################################################---- %purpose: disable all relational constraints on tables owned by the user that executes this script---- #############################################################################################---- requires oracle 8.1--------------------------------------------------------------------------------promptprompt generating script to disable the relational constraints...

set pagesize 0set feedback offset termout offset linesize 100set trimspool onset wrap on

spool disable_relational_constraints.lst.sql

prompt promptprompt prompt disabling relational constraints...

select 'prompt ... disabling constraint '||constraint_name||' on table '||table_name, 'alter table '||table_name||' disable constraint '||constraint_name||';'from user_constraintswhere constraint_type = 'r'/

spool offset feedback on

Page 12: Oracle Db a Scripts One in All

set termout onspool disable_relational_constraints.log@disable_relational_constraints.lst.sqlspool 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) mbfrom dba_segmentswhere (bytes > 10000000) and (segment_type <> 'index')order by bytes/-- #############################################################################################---- %purpose: displays an ordered list of the indexes on a given table---- #############################################################################################--set linesize 120 verify off

select i.table_name "table", i.index_name "index", i.uniqueness "type", c.column_position "n", c.column_name "column" from all_indexes i, all_ind_columns c where i.table_name like upper('&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/

-- #############################################################################################

Page 13: Oracle Db a Scripts One in All

---- %purpose: displays database resource usage statistics (whole instance or session)---- #############################################################################################--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]: 'promptprompt statistic changeprompt --------- ------;--declare max_statistic# number; 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;beginselect max(statistic#) into max_statistic# from v$statname;current_second := to_number(to_char(sysdate,'sssss'));while to_number(to_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# loop 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.sid = &&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 stat_name, stat_class from v$statname v where v.statistic# = i;

Page 14: Oracle Db a Scripts One in All

if stat_class in (1,8,64,128) then dbms_output.put(rpad(stat_name,52)); dbms_output.put_line( to_char(second_stat(i) - first_stat(i),'9,999,990')); end if; end if; end loop;end;/promptundef sid intervalset feedback on-- #############################################################################################---- %purpose: displays the execution plan for a sql dml statement---- the sql statement should be in a separate text file,-- with either a ";" at the end of the line or a "/" on-- the next line. a plan_table table is required.---- usage: sqlplus 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 onexplain plan for@&1set 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 || ' ' || decode(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) otherfrom plan_table

Page 15: Oracle Db a Scripts One in All

start with id = 0 connect by prior id = parent_id/--rollback;--set feedback on-- #############################################################################################---- %purpose: drop all objects of the user that executes this script.---- #############################################################################################---- akadia sql utility scripts---- requires oracle 8.1--------------------------------------------------------------------------------

promptprompt generating script to drop the objects...

set pagesize 0set feedback offset termout offset linesize 100set trimspool onset wrap on

spool drop_user_objects.lst.sql

prompt promptprompt prompt dropping public synonyms...

select 'prompt ... dropping public synonym '||synonym_name, 'drop public synonym '||synonym_name||';'from all_synonymswhere table_owner = ( select user from dual )/

prompt promptprompt prompt dropping relational constraints...

select 'prompt ... dropping constraint '||constraint_name||' on table '||table_name, 'alter table '||table_name||' drop constraint '||constraint_name||';'from user_constraintswhere constraint_type = 'r'/

prompt promptprompt prompt dropping remaining user objects...

Page 16: Oracle Db a Scripts One in All

select 'prompt ... dropping '||object_type||' '||object_name, 'drop '||object_type||' '||object_name||';'from user_objectswhere object_type != 'index'/

spool offset feedback onset termout onspool drop_user_objects.log@drop_user_objects.lst.sql

promptprompt all database objects of the user dropped.prompt please review the log file drop_user_objects.log in the current directory.promptprompt count of remaining objects:

set feedback off

select count(*) remaining_user_objectsfrom user_objects/

set feedback onspool off-- #############################################################################################---- %purpose: enable all relational constraints on tables owned by the user that executes this script---- #############################################################################################---- requires oracle 8.1--------------------------------------------------------------------------------promptprompt generating script to enable disabled relational constraints...

set pagesize 0set feedback offset termout offset linesize 100set trimspool onset wrap on

spool enable_relational_constraints.lst.sql

prompt promptprompt prompt enabling relational constraints...

select 'prompt ... enabling constraint '||constraint_name||' on table '||table_name, 'alter table '||table_name||' enable constraint '||constraint_name||';'

Page 17: Oracle Db a Scripts One in All

from user_constraintswhere constraint_type = 'r'and status = 'disabled'/

spool offset feedback onset termout onspool enable_relational_constraints.log@enable_relational_constraints.lst.sqlspool off-- #############################################################################################---- %purpose: extensive partitioning examples for oracle8 partition option---- example 1: - the partition key is part of the primary key-- - partition key: [date_cdr]-- - primary 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 maxextents 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 minextents 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 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- local non prefixed primary key (unique)

Page 18: Oracle Db a Scripts One in All

---- der linke teil des index stimmt nicht-- mit dem partition-key [date_cdr] berein�-------------------------------------------------------------------alter table cdr add ( constraint pk_cdr primary key (bkg_id,date_cdr)using indexlocal(partition cdr_01_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_02_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_04_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_05_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0))/----------------------------------------------------------------------- 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 minextents 1 maxextents unlimited) pctfree 0, partition cdr_02_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_04_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_05_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/----------------------------------------------------------------------- local prefixed index (unique)---- der linke teil des index stimmt-- mit dem partition-key [date_cdr] berein, deshalb kann der�

Page 19: Oracle Db a Scripts One in All

-- 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 maxextents unlimited) pctfree 0, partition cdr_02_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_04_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_05_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/alter table cdr add ( constraint cdr_idx_2 unique (date_cdr,bkg_id))/----------------------------------------------------------------------- local prefixed index (unique)---- der linke teil des index entspricht dem partition-key [date_cdr].-- deshalb kann der index unique sein.---------------------------------------------------------------------create unique index cdr_idx_3 on cdr (date_cdr)local(partition cdr_01_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_02_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_03_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_04_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition cdr_05_1999 tablespace idx_cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- example 2: - der partition key ist nicht teil des primary keys-- - partition key: [date_req]-- - primary key: [bkg_id,req_id]---------------------------------------------------------------------drop table req cascade constraints;

Page 20: Oracle Db a Scripts One in All

--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) (partition req_01_1999 values less than (to_date('01.02.1999','dd.mm.yyyy')) tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_02_1999 values less than (to_date('01.03.1999','dd.mm.yyyy')) tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, 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 0, partition req_04_1999 values less than (to_date('01.05.1999','dd.mm.yyyy')) tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_05_1999 values less than (maxvalue) tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- 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 storage (initial 500k next 500k minextents 1 maxextents unlimited pctincrease 0 freelists 2))/alter table req drop primary key/--------------------------------------------------------------------- globaler primary key, ein "must" f r Primary keys welche ohne�-- den partition-key auskommen m ssen.�---------------------------------------------------------------------create unique index pk_req on req (bkg_id,req_id)globalpartition by range (bkg_id,req_id)(partition pk_req_01

Page 21: Oracle Db a Scripts One in All

values less than (100000,100000) tablespace idx_bkg storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition pk_req_02 values less than (200000,200000) tablespace idx_bkg storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition pk_req_03 values less than (300000,300000) tablespace idx_bkg storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition pk_req_04 values less than (maxvalue,maxvalue) tablespace idx_bkg storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/alter table req add ( constraint pk_req primary key (bkg_id,req_id))/--------------------------------------------------------------------- local prefixed index (unique w re m glich)� �---- der linke teil des index stimmt mit dem partition-key-- [date_req] berein.�---------------------------------------------------------------------create index idx_req_1 on req (date_req,req_id)local(partition req_01_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_02_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_03_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_04_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_05_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- local prefixed index nur auf partition-key---- der index entspricht 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 maxextents unlimited) pctfree 0, partition req_02_1999 tablespace idx_req

Page 22: Oracle Db a Scripts One in All

storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_03_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_04_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_05_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- local non prefixed index---- der linke teil des index stimmt nicht mit dem-- partition-key date_req berein�---------------------------------------------------------------------create index idx_req_3 on req (req_id,date_req)local(partition req_01_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_02_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_03_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_04_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_05_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- local non prefixed index---- der index ist ein beliebiges attribut---------------------------------------------------------------------create index idx_req_4 on req (req_id)local(partition req_01_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_02_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_03_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_04_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_05_1999 tablespace idx_req

Page 23: Oracle Db a Scripts One in All

storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- bitmapped indexe---- 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 (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_02_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_03_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_04_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_05_1999 tablespace idx_req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--------------------------------------------------------------------- anf gen von zwei neuen partitionen�---------------------------------------------------------------------alter table req split 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 maxextents unlimited) pctfree 0, partition req_05_1999_2 tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/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_date('30.06.1999','dd.mm.yyyy')) into (partition req_06_1999_1 tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0, partition req_06_1999_2 tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0)/--

Page 24: Oracle Db a Scripts One in All

-- die local indexes wurden auch aufgeteilt und m ssen�-- nun wieder auf die gleichen 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 index idx_req_1 rename partition req_06_1999_1 to req_06_1999/alter index idx_req_1 rename partition req_06_1999_2 to req_07_1999/--alter index idx_req_2 rename partition req_05_1999_1 to req_05_1999/alter index idx_req_2 rename partition req_06_1999_1 to req_06_1999/alter index idx_req_2 rename partition req_06_1999_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_1999/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 rename partition req_06_1999_2 to req_07_1999/--alter index idx_bm_req_1 rename partition 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

Page 25: Oracle Db a Scripts One in All

/---- rebuild aller local indexes--alter table req modify partition req_01_1999 rebuild unusable local indexes/alter table req modify partition req_02_1999 rebuild unusable local indexes/alter table req modify partition req_03_1999 rebuild unusable local indexes/alter table req modify partition req_04_1999 rebuild unusable local indexes/alter table req modify partition req_05_1999 rebuild unusable local indexes/alter table req modify partition req_06_1999 rebuild unusable local indexes/alter table req modify partition req_07_1999 rebuild unusable local indexes/--------------------------------------------------------------------- anf gen von einer neuen partition f r den primary key� �---------------------------------------------------------------------alter index pk_req split partition pk_req_04 at (400000,400000) into (partition pk_req_04_1 tablespace req storage (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_req_04/alter index pk_req rename partition pk_req_04_2 to pk_req_05/---- rebuild des primary keys einzeln f r jede partition�--alter index pk_req rebuild partition pk_req_01/alter index pk_req rebuild partition pk_req_02/alter index pk_req rebuild partition pk_req_03/alter index pk_req

Page 26: Oracle Db a Scripts One in All

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 schen wir die�-- letzte partition zuerst. die local indexes werden beim-- hinzuf gen von partitions automatisch auch mit einer�-- indexpartition erg nzt (sehr gute wartbarkeit).�--alter table cdr drop partition cdr_05_1999;alter table cdr add partition cdr_05_1999 values less than (to_date('01.06.1999','dd.mm.yyyy')) tablespace cdr storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 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 values 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 (der 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 storage (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.mm.yyyy')) tablespace req storage (initial 1k next 100m minextents 1 maxextents unlimited) pctfree 0;---- move partition--alter table req move partition req_08_1999 tablespace tab storage (initial 1k next 1k minextents 1 maxextents unlimited) pctfree 0;---- indexe m ssen rebuilded werden, da sie durch move�

Page 27: Oracle Db a Scripts One in All

-- 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 partition req_08_1999/-- #############################################################################################---- %purpose: flush shared pool when it reaches 60-70% of it's capacity---- use: sys-user---- #############################################################################################---- on a recent project we had a problem where performance would start-- acceptable at the beginning of the day and by mid-day would be-- totally unacceptable. investigation showed that the third party-- application that ran on top of the oracle database was generating-- ad hoc sql without using bind variables. this generation of ad hoc-- 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 for 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, resulting that all other query returned again in less than a second.---- it was determined that an automatic procedure was needed to monitor-- the shared pool and flush 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, persistent_mem, runtime_memfrom sys.v_$sqlarea a, dba_users bwhere a.parsing_user_id = b.user_id;

create or replace procedure flush_it as

Page 28: Oracle Db a Scripts One in All

cursor get_share is select sum(sharable_mem) from sys.sql_summary;

cursor get_var is select value from v$sga where name like 'var%';

cursor get_time is select sysdate from dual;

todays_date date; mem_ratio number; share_mem number; variable_mem number; cur integer; sql_com varchar2(60); row_proc number;

begin

open get_share; open get_var;

fetch get_share into share_mem; dbms_output.put_line('share_mem: '||to_char(share_mem));

fetch get_var into variable_mem; dbms_output.put_line('variable_mem: '||to_char(variable_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 shared_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 commands:

declare job number;begin dbms_job.submit(job,'flush_it;',sysdate,'sysdate+1/24');end;/-- ##################################################################################

Page 29: Oracle Db a Scripts One in All

###########---- %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 :---- dept = --------------------------crime [5]-- emp_no = ------------------------1 [1]-- first_name = --------------------john [4]-- join_date = ---------------------02/01/1999 17:38:56 [9]-- last_name = ---------------------doe [3]-- middle_initial = ----------------p [1]---- press return to continue---- #############################################################################################

col eol newlineset head off pages 0 numf 9999999999.99set lines 200 wrap on trimspool onprompt note : long/raw/lob columns will not be displayedpromptset feedback off verify off echo offaccept tab prompt "enter table name: [example: emp] "promptprompt to enter strings in the where clause or order by, enclose itprompt within '''' single quotes instead of the usual single quoteprompt [example: ename = ''''james'''']promptaccept wher prompt "enter where clause {default is none}: "accept oner prompt "enter owner {default is current user}: "accept sortorder prompt "enter order by clause <1,3,5,..> {default is unordered}: "promptprompt press return ...promptset termout offcol column_name noprintcol wherstmt new_val wherclausecol ordby new_val orderbycol usr new_val objuserselect 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 feedback off verify off echo off termout on trimspool on' eolfrom

Page 30: Oracle Db a Scripts One in All

dba_tab_columnswhere 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,'date','to_char('||column_name||','||''''||'mm/dd/yyyy hh24:mi:ss'||''''||')', column_name) || ' '|| decode(data_type,'number',decode(sign(data_scale-1),-1,' ||', ' ||'),' '||' ||')|| ''''|| ' ['||''''||'||'|| ' to_char(nvl(length('||column_name||'),0))'|| '||'||''''||']'||''''||' eol,' clfrom dba_tab_columnswhere 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 = '&objuser' and table_name = upper('&tab'))unionselect column_name, 'rpad('||''''||column_name||' = '|| ''''||',33,'||''''||'-'||''''||') '||'||'|| decode(data_type,'date','to_char('||column_name||','||''''||'mm/dd/yyyy hh24:mi:ss'||''''||')', column_name) || ' '|| decode(data_type,'number',decode(sign(data_scale-1),-1,' ||', ' ||'),' '||' ||')|| ''''|| ' ['||''''||'||'|| ' to_char(nvl(length('||column_name||'),0))'|| '||'||''''||']'||''''||' eol'|| ' from &objuser..&tab '||' &wherclause '||' &orderby ;' clfrom dba_tab_columnswhere 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 = '&objuser' and table_name = upper('&tab'))order by column_name;spool offstart vertdispclear colu-- #############################################################################################

Page 31: Oracle Db a Scripts One in All

---- %purpose: generate 'create table' script for an existing table in the database---- use: system, sys or user having select any table system privilege---- #############################################################################################--set serveroutput on size 200000set echo offset feedback offset verify offset showmode off--accept l_user char prompt 'username: 'accept l_table char prompt 'tablename: '--declare cursor tabcur is select table_name,owner,tablespace_name, initial_extent,next_extent, pct_used,pct_free,pct_increase,degree from 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' || '(' || data_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;-- colcount 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; --

Page 32: Oracle Db a Scripts One in All

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); colcount:=colcount+1; -- if (colcount < maxcol) then dbms_output.put_line(','); else 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 '||tabrec.pct_increase); dbms_output.put_line(' )'); dbms_output.put_line('parallel '||tabrec.degree); dbms_output.put_line('/'); end loop;end;/-- #############################################################################################---- %purpose: generate insert statements for existing data in a table---- author: [email protected] #############################################################################################--prompt ==========================================================================prompt generate insert statements for existing data in a tableprompt ==========================================================================promptprompt you'll be prompted for the following:prompt - table_name: the name of the table to generate statements (case insensitive)prompt - col1: the name of a column you want to fill with fixed data (case insensitive)prompt . - [enter]: do not use this functionality

Page 33: Oracle Db a Scripts One in All

prompt - col1_value: the value for the column above (case sensitive)prompt . - enter string values within two single quotes: ''example''prompt . - [enter]: do not use this functionalityprompt - col2: the name of a column you want to fill with fixed data (case insensitive)prompt . - [enter]: do not use this functionalityprompt - col2_value: the value for the column above (case sensitive)prompt . - enter string values within two single quotes: ''example''prompt . - [enter]: do not use this functionalityprompt

set feedback offset trimspool onset linesize 255

create or replace procedure genins(p_table in varchar ,p_default_col1 varchar default null ,p_default_col1_value varchar default null ,p_default_col2 varchar default 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; ignore 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_columns 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_default_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_col1_value varchar ,c_default_col2 varchar

Page 34: Oracle Db a Scripts One in All

,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_name||',null,''null'','|| decode(data_type ,'varchar2','''''''''||'||column_name ||'||''''''''' ,'date' ,'''to_date(''''''||to_char('||column_name||',''yyyy-mm-dd 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_query,1,length(l_query)-7); return l_query || ' from ' || p_table; end; --begin l_column_list := get_cols(p_table); l_query := get_query(p_table,upper(p_default_col1),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 1000000exec genins('&table_name','&col1','&col1_value','&col2','&col2_value');set serveroutput off

drop procedure genins;set feedback on-- #############################################################################################---- %purpose: generate script to coalesce free space in cluttered tablespaces

Page 35: Oracle Db a Scripts One in All

---- #############################################################################################--select a1.tablespace_name,count(*) nbr_cont_wholes from sys.dba_free_space a1, sys.dba_free_space a2 where a1.tablespace_name=a2.tablespace_name and a1.block_id+a1.blocks = a2.block_id group by a1.tablespace_name/set heading offspool alter_ts_coal.sqlselect 'alter tablespace '||a1.tablespace_name||' coalesce;' from sys.dba_free_space a1, sys.dba_free_space a2 where a1.tablespace_name=a2.tablespace_name and a1.block_id+a1.blocks = a2.block_id group by a1.tablespace_name/spool offset 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.extents "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 [bytes] extents rs-size [bytes] number waits---------- ---------------- ---------- --------------- ------------rbs01 8597504 21 409405 1616rbs02 8597504 21 409405 4125rbs03 8597504 21 409405 3992rbs04 8597504 21 409405 4174rbs05 8597504 21 409405 3617rbs06 8597504 21 409405 3843rbs07 8597504 21 409405 3715rbs08 8597504 21 409405 3730rbs09 8597504 21 409405 25699rbs10 8597504 21 409405 3635

Page 36: Oracle Db a Scripts One in All

new tuning session: (rollback segments with 5 mb size)

name tot-size [bytes] extents rs-size [bytes] number waits---------- ---------------- ---------- --------------- ------------rbs01 104853504 20 5242675 1715rbs02 104853504 20 5242675 1835rbs03 104853504 20 5242675 1338rbs04 104853504 20 5242675 1499rbs05 104853504 20 5242675 1572rbs06 104853504 20 5242675 1628rbs07 104853504 20 5242675 1533rbs08 104853504 20 5242675 1689rbs09 104853504 20 5242675 1461rbs10 104853504 20 5242675 1663

2). rollback contention-----------------------select name,gets,waits, to_char(((gets-waits)*100)/gets,'999.9999') hit_ratio from v$rollstat s, v$rollname r where s.usn = r.usnorder by r.name;

old tuning session: (rollback segments with 400 kb size)

name gets waits hit_ratio------------------------------ ---------- ---------- ---------rbs01 5314092 1643 99.9691rbs02 10363748 4157 99.9599rbs03 10459920 4017 99.9616rbs04 10962299 4184 99.9618rbs05 9469712 3649 99.9615rbs06 10218019 3889 99.9619rbs07 9796463 3736 99.9619rbs08 9900727 3739 99.9622rbs09 13130819 25721 99.8041rbs10 9456272 3673 99.9612

new tuning session: (rollback segments with 5 mb size)

name gets waits hit_ratio------------------------------ ---------- ---------- ---------rbs01 5837671 1719 99.9706rbs02 6151758 1835 99.9702rbs03 5451355 1338 99.9755rbs04 5105157 1499 99.9706rbs05 5333881 1574 99.9705rbs06 6070279 1631 99.9731rbs07 5611779 1533 99.9727rbs08 6097782 1692 99.9723rbs09 5558601 1462 99.9737rbs10 6418860 1663 99.9741

3). compare rollback segment waits with total number of gets------------------------------------------------------------rollback segment waits

select v.class, v.count

Page 37: Oracle Db a Scripts One in All

from v$waitstat v where class in ('system undo header','system undo block', 'undo 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','consistent gets');

old tuning session: (much waits compared with total gets)

class count------------------ ----------system undo header 0system undo block 0undo header 74880undo block 21618

total gets---------------- 8,896,140,872

new tuning session: (much waits compared with total gets, not better)

class count------------------ ----------system undo header 0system undo block 0undo header 24138undo block 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 name 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 rollbacks 128 29'131

Page 38: Oracle Db a Scripts One in All

a low number of rollbacks initiate a high nunber of waits !

new tuning session

statistic# name class value---------- -------------------------------------------------- ---------- ---------- 5 user rollbacks 1 51 113 rollback changes - undo records applied 128 111886 114 transaction rollbacks 128 13649

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.extents, x.extends,x.waits,x.shrinks, x.wrapsfrom sys.v_$rollstat x, sys.v_$rollname r, sys.v_$session s, sys.v_$transaction twhere t.addr = s.taddr (+)and x.usn (+) = r.usnand t.xidusn (+) = r.usnorder by r.usn;

old tuning session

usn name osuser user sid extents extends waits shrinks wraps---------- ---------- --------------- --------------- ---------- ---------- ---------- ---------- ---------- ---------- 0 system 4 0 0 0 0 2 rbs01 poseidon vp_link 55 21 321 1703 34 3448 3 rbs02 ota dispatcher 35 21 370 4175 42 6589 4 rbs03 poseidon vp_link 59 21 445 4074 53 6981 5 rbs04 poseidon vp_link 56 21 262 4252 33 7073 6 rbs05 bscs smh_link 76 21 195 3772 22 5847 7 rbs06 21 291 4044 34 6665 8 rbs07 21 259 3803 31 6336 9 rbs08 poseidon vp_link 57 21 529 3820 64 6789 10 rbs09 poseidon vp_link 54 21 599 25839 69 8153 11 rbs10 21

Page 39: Oracle Db a Scripts One in All

398 3772 45 5878

new tuning session

usn name osuser user sid extents extends waits shrinks wraps---------- ---------- --------------- --------------- ---------- ---------- ---------- ---------- ---------- ---------- 0 system 4 0 0 0 1 1 rbs10 20 0 1681 0 299 2 rbs01 20 0 1731 0 277 3 rbs02 poseidon vp_link 93 20 0 1850 0 288 4 rbs03 poseidon vp_link 92 20 0 1338 0 248 5 rbs04 poseidon vp_link 86 20 0 1499 0 232 6 rbs05 bscs smh_link 94 20 0 1583 0 258 7 rbs06 bscs smh_link 113 20 0 1645 0 282 8 rbs07 poseidon vp_link 70 20 0 1533 0 260 9 rbs08 20 0 1694 0 274 10 rbs09 20 0 1483 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, sqlstatements etc. each namespace (or library) contains differenttypes of object. the figures here give a quick summary of theusage of each namespace. the most useful indicator here is thereloads column.

nearly no reloads, shared pool is ok.

****************************2). cpu used by this session****************************

Page 40: Oracle Db a Scripts One in All

by comparing the relative time spent waiting on each wait eventand the cpu used by this session, we can see where the oracleinstance is spending most of its time.

statistic total per transact per logon per second--------------------------- ------------ ------------ ------------ ------------cpu used by this session 542660 1.18 2647.12 95.22parse time cpu 244 0 1.19 .04

***********************************3). locating cpu-heavy sql (top 15)***********************************

the statement below finds sql statements which access database buffersa lot. such statements are typically heavy on cpu usage because they areprobably looking 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_gets - disk_reads) / buffer_gets, 2) * 100 "hitratio", sql_text from v$sqlarea where buffer_gets > 10000000 and executions > 1000000order by buffer_gets desc;

disk-reads buffer-gets executions gets/exec reads/exec hitratio---------- ----------- ---------- ---------- ---------- ---------- 14607 40882602 3211863 12.7286257 .004547828 100sql-text---------------------------------------------------------------------------update sscrequest set msgstate=:b1,response=:b2,servicestate=:b3,returncode=:b4,inipara=:b5,processtime=sysdate where requestid=:b6

disk-reads buffer-gets executions gets/exec reads/exec hitratio---------- ----------- ---------- ---------- ---------- ---------- 188249 34923996 1528920 22.8422651 .123125474 99sql-text---------------------------------------------------------------------------update sscorder set state=:b1,returncode=:b2,priority=:b3,processtime=sysdate,deferred=to_date(:b4,'yyyymmddhh24miss')where requestid=:b5

**********************************************************4). locating cpu-heavy sessions (cpu used by this session)**********************************************************

select substr(a.sid,1,5) "sid", substr(a.process,1,7) "process", substr(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.statistic#=s.statistic# and v.sid = a.sid and v.value > 1000order by v.value desc;

Page 41: Oracle Db a Scripts One in All

sid process user cpu used by this session----- ------- -------------------- ------------------------62 12602 sscdsp 279115382 10949 sscsmh 1591242103 12603 sscdsp 191758110 16629 dispatcher 5067783 9913 smh_link 4829669 12430 sscfsm 4412359 12265 sscfsm 4381260 10997 sscfsm 4372251 16628 dispatcher 3586571 11017 sscsmh 3388153 12138 sscfsm 27938

**********************5). common wait events**********************

system wide wait events for non-background processes (pmon,smon, etc). times are in hundreths of seconds. each one ofthese is a context switch which costs cpu time. by looking atthe total time you can often determine what is the bottleneckthat processes are waiting for. this shows the total time spentwaiting for a specific event and the average time per wait onthat event.

ignore any 'idle' wait events. common idle wait events include:

client message - process waiting for data from thesql*net message from client client applicationsql*net more data from clientrdbms ipc message - usually background process waiting for workpipe get - dbms_pipe read waiting for datanull event - miscellaneouspmon timer - pmon waiting for worksmon timer - smon waiting for workparallel query dequeue - waiting for input (discussed later)

event name count total time avg time-------------------------------- ------------- ------------- -------------log file sync 527031 2076364 3.94db file sequential read 379096 948531 2.5write complete waits 1549 90879 58.67db file scattered read 508925 55312 .11buffer busy waits 6070 44408 7.32log file switch completion 276 13875 50.27latch free 2828 5517 1.95enqueue 284 2498 8.8log buffer space 102 753 7.38buffer deadlock 24 48 2control file sequential read 134 16 .12

-----------------------------------------system wide waits for "buffer busy waits"-----------------------------------------this wait happens when a session wants to access a databaseblock in the buffer cache but it cannot as the buffer is "busy".the two main cases where this can occur are:

Page 42: Oracle Db a Scripts One in All

- another session is reading the block into the buffer- another session holds the buffer in an incompatible mode to our request

if the time spent waiting for buffers is significant then we need todetermine which segment/s is/are suffering from contention.the "buffer busy wait statistics" section of the bstat/estat showswhich block type/s are seeing the most contention. this informationis derived 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, class from v$waitstatorder 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 information can be obtained from the internalview x$kcbfwait thus:

select count, file#, substr(name,1,50) from x$kcbfwait, v$datafile where indx + 1 = file# order by count;

count file# substr(name,1,50)---------- ---------- -------------------------------------------------- 0 3 /data/ota/db1/otasicap/data/temp01.dbf 0 4 /data/ota/db1/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/otasicap/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/data/idx_sccorder_03.dbf 1181 11 /data/ota/db2/otasicap/data/idx_sccorder_02.dbf 5337 7 /data/ota/db2/otasicap/data/idx_01.dbf 6535 8 /data/ota/db1/otasicap/data/tbs_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/otasicap/data/rbs01.dbf 47124 18 /data/ota/db2/otasicap/data/rbs02.dbf 171997 6 /data/ota/db1/otasicap/data/data01.dbf

this shows the file/s with the most waits (at the bottom of the list)

Page 43: Oracle Db a Scripts One in All

so by combining the two sets of information we know what blocktype/s in which file/s are causing waits.the segments in each file can be seen using a query like:

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 segment-name segment-type------------------------------ ------------------------------ -----------------dispatcher archivio_ssc_sms_ccbs tabledispatcher idx_msisdn_reloadfix indexdispatcher reloadfix tabledispatcher sscms_mscount_5 tabledispatcher ssc_changes tabledispatcher ssc_sms_ccbs tabledispatcher ssc_sms_ccbs_old tableorastat segment_info tablesysadm bkp_99_state_sscorder tablesysadm sscapps tablesysadm ssccdr tablesysadm sscconf tablesysadm sscrequest tablesysadm sscresponse tablesysadm sscsmbuf table

if there are a large number of segments of the type listed thenmonitoring v$session_wait may help isolate which object is causingthe waits. repeatedly run the following statement and collect theoutput. after a period of time sort the results to see whichfile & blocks are showing contention:

select p1 "file", p2 "block", p3 "reason" from v$session_wait where event='buffer busy waits';

file block reason---------- ---------- ---------- 18 79362 1012 18 67842 1016

file block reason---------- ---------- ---------- 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 from

Page 44: Oracle Db a Scripts One in All

a disk sort area may use this wait event when reading severalcontiguous blocks. remember io is a normal activity so you arereally interested in unnecessary or slow io activity.

==> tune sql statements

-----------------------------------------------------------------system wide waits for "db file scattered read" (full table scans)-----------------------------------------------------------------this wait happens when a session is waiting for a multiblockio to complete. this typically occurs during full table scansor index fast full scans. oracle reads up todb_file_multiblock_read_count consecutive blocks at a timeand scatters them 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 significantthen we need to determine which segment/s we are performingthe reads against. see the "tablespace io" and "file io"sections of the estat report to get information on whichtablespaces / files are servicing multiblock reads (blks_read/reads>1).

it is probably best at this stage to find which sessionsare performing scans and trace them to see if the scansare expected or not. this statement can be used to seewhich 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_waited from v$session_event v, v$session a where v.event='db file scattered read' and v.total_waits > 0 and a.sid = v.sid order by v.total_waits desc;

sid process user total_waits time_waited----- ------- -------------------- ----------- -----------109 12533 smh_link 136172 6401111 10391 dispatcher 30045 3390120 31320 vp_link 5792 78975 4214116 vp_link 5760 371101 4290951 sysadm 1582 46285 11165 sysadm 1566 5226 9832 570 84082 10949 sscsmh 179 88108 52360 vp_link 85 65115 8781 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 butthis should be tested.db_file_multiblock_read_count should generally be made as largeas possible. the value is usually capped by oracle and so itcannot be set too high. the 'capped' value differs between platformsand versions and usually depends on the settings of db_block_sizeand use_readv.

Page 45: Oracle Db a Scripts One in All

current settings

use_readv boolean falsedb_file_multiblock_read_count integer 32

----------------------------------------------system wide waits for "enqueue" (local 'lock')----------------------------------------------a wait for an enqueue is a wait for a local 'lock'. the count andaverage wait times for this wait-event can be misleading as "enqueue"waits re-arm every few seconds. to qualify how many waits have reallyoccurred you need the enqueue waits statistic from the statisticssection of the estat report.

to determine which enqueues are causing the most waits system-widelook at view x$ksqst

select ksqsttyp "lock", ksqstget "gets", ksqstwat "waits" from x$ksqst where ksqstwat>0;

lo gets waits-- ---------- ----------cf 3720 2ci 1936 2cu 379 1dx 23582708 7st 4591 20tx 19710183 16189

tx transaction lock

generally due to application or table setup issues

tm dml enqueue

generally due to application issues, particularly ifforeign key constraints have 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 criticalbits of code. as a latch wait is typically quite short it ispossible to see a large number of latch waits which onlyaccount for a small percentage of time.if the time spent waiting for latches is significant then weneed to determine which latches are suffering from contention.the bstat/estat section on latches shows latch activity inthe period sampled. this section of the estat report is basedon view v$latch gives a summary of latch activity since instancestartup and can give an indication of which latches are responsible

Page 46: Oracle Db a Scripts One in All

for the most time spent waiting for "latch free" thus:

select latch#, substr(name,1,30) gets, misses, sleeps from v$latch where sleeps>0 order by sleeps desc;

latch# gets misses sleeps---------- ------------------------------ ---------- ---------- 11 cache buffers chains 1619686 103490 18 redo allocation 1934934 8607 37 global tx hash mapping 33542 4493 39 library cache 325559 2555 19 redo copy 18711 2326 8 enqueues 593898 1781 2 session allocation 337507 1506 15 cache buffers lru chain 23440 1411 9 enqueue hash chains 98115 1069 29 undo global data 264600 791 16 system commit number 210693 752 27 transaction allocation 87931 461 7 messages 113626 315 25 dml lock allocation 29710 206 26 list of block allocation 29313 176 4 session idle bit 34286 155 13 multiblock read objects 5452 35 32 row cache objects 326 9 35 global tx free list 1956 7 6 modify parameter values 2 3 38 shared pool 31 3 0 latch wait list 219 2 50 parallel query stats 2 1

cache buffers chains latches

individual block contention can show up as contention for one of theselatches. each cache buffers chains latch covers a list of buffers inthe buffer cache.

---------------------------------------------system wide waits for "log file space/switch"---------------------------------------------there are several wait events which may indicate problems withthe redo buffer and redo log throughput:

log buffer spacelog file switch (checkpoint incomplete)log file switch (archiving needed)log file switch/archivelog file switch (clearing log file)log file switch completionswitch logfile command

increase the log_buffer size until there is no incrementalbenefit (sizes > 1mb are unlikely to add any benefit)

for all other waits:

Page 47: Oracle Db a Scripts One in All

- ensure redo logs are on fast disks (not raid5)- ensure redo logs are large enough to give a sensible gap between log switches. a 'rule-of-thumb' is to have one log switch every 15 to 30 minutes.- ensure the archiver process is running and keeping up.

-------------------------------------system wide waits for "log file sync"-------------------------------------this wait happens when a commit (or rollback) is issued andthe session has to wait for the redo entry to be flushed todisk 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 complete waits"--------------------------------------------this wait happens when a requested buffer is being written to diskwe cannot use the buffer while it is being written.if the time spent waiting for buffers to be written issignificant then note the "average write queue length"if this too is large then the the cache aging rate istoo 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 length gives an indication of whether the cacheis being cleared of dirty blocks fast enough or not. unless the systemis very high throughput the write queue should never be very large.as a general guideline if the average write queue is in double figuresit is certainly worth finding where the activity is coming from.if the figure is in single digits there may still be un-necessaryactivity in the cache.

the 2 main ways to improve the write queue length are:

eliminate any unnecessary write io from going via the cache.improve dbwr throughput. eg: use asynchronous writes,multiple database writer processes, larger block write batch.

anything above 100 indicates that the dbwr ishaving 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 in ( 'summed dirty queue length','write requests') and value > 0;

average write queue length (should be 0)

Page 48: Oracle Db a Scripts One in All

----------------------------------------0.35044

*****************************6). tablespace io and file io*****************************

table_space tablespace namefile_name file name in this tablespacereads number of read calls to the osblks_read number of blocks read. the above two differ only when multi-block reads are being performed. eg: on full table scans we read up to db_file_multiblock_read_count blocks per read.read_time total time for the reads in 1/100ths of a secondwrites number of os write callsblks_wrt number of blocks writtenwrite_time write time in 1/100ths of a second. nb: this figure may be incorrect.

table_space reads blks_read read_time writes blks_wrt write_time megabytes----------------- ------- ---------- ---------- ---------- ---------- ---------- ----------data 24487 88794 4713 17011 17011 531654 524idx 6844 6844 26326 38219 38219 1454912 524rbs 2 2 2 102702 102702 5333108 1598system 101 152 71 97 97 3542 105tbs_sccorder 684066 6344009 86376 46697 46697 2081706 3222tbs_sccorder_idx 125173 125174 847903 228494 228494 12198710 3222tbs_sscms 28801 28801 41554 39439 39439 1235851 2148tbs_sscms_idx 20732 20732 5126 231 231 6541 2148temp 51 725 27 89 678 242 1049tools 0 0 0 0 0 0 105users 0 0 0 15 15 410 105

read-time per block in [ms] = ((read_time/100) / blks_read) * 1000

tbs_sccorder: ((86'376/100)/6'344'009)*1000 = 0.13 ms (very fast)tbs_sccorder_idx: ((847'903/100)/125'174)*1000 = 67.73 ms (very slow)tbs_sscms: ((41'554/100)/28'801)*1000 = 14.43 ms (ok)tbs_sscms_idx: ((5'126/100)/)20'732*1000 = 2.47 ms (very fast)

table_space file_name reads blks_read read_time writes blks_wrt write_time megabytes----------------- ------------------------------------------------ ----------

Page 49: Oracle Db a Scripts One in All

---------- ---------- ---------- ---------- ---------- ----------data /data/ota/db1/otasicap/data/data01.dbf 24487 88794 4713 17011 17011 531654 524idx /data/ota/db2/otasicap/data/idx_01.dbf 6844 6844 26326 38219 38219 1454912 524rbs /data/ota/db1/otasicap/data/rbs01.dbf 1 1 0 23922 23922 854404 524rbs /data/ota/db2/otasicap/data/rbs02.dbf 1 1 2 78780 78780 4478704 1074system /data/ota/db1/otasicap/data/system01.dbf 101 152 71 97 97 3542 105tbs_sccorder /data/ota/db1/otasicap/data/tbs_sccorder_01.dbf 242174 2841155 34210 24178 24178 806926 1074tbs_sccorder /data/ota/db1/otasicap/data/tbs_sccorder_02.dbf 282835 2075092 41336 22519 22519 1274780 1074tbs_sccorder /data/ota/db1/otasicap/data/tbs_sccorder_03.dbf 159057 1427762 10830 0 0 0 1074tbs_sccorder_idx /data/ota/db2/otasicap/data/idx_sccorder_01.dbf 23354 23354 49920 52053 52053 1963087 1074tbs_sccorder_idx /data/ota/db2/otasicap/data/idx_sccorder_02.dbf 84367 84368 743566 124286 124286 8090752 1074tbs_sccorder_idx /data/ota/db2/otasicap/data/idx_sccorder_03.dbf 17452 17452 54417 52155 52155 2144871 1074tbs_sscms /data/ota/db1/otasicap/data/tbs_sccms_01.dbf 12889 12889 19041 17960 17960 562416 1074tbs_sscms /data/ota/db1/otasicap/data/tbs_sccms_02.dbf 15912 15912 22513 21479 21479 673435 1074tbs_sscms_idx /data/ota/db2/otasicap/data/idx_sccms_01.dbf 20428 20428 4738 184 184 4997 1074tbs_sscms_idx /data/ota/db2/otasicap/data/idx_sccms_02.dbf 304 304 388 47 47 1544 1074temp /data/ota/db1/otasicap/data/temp01.dbf 51 725 27 89 678 242 1049tools /data/ota/db1/otasicap/data/tools.dbf 0 0 0 0 0 0 105users /data/ota/db1/otasicap/data/users.dbf 0 0 0 15 15 410 105

**********************7). fragmented objects**********************

set feed offset pagesize 5000break on owner skip 1 on tablespace_name on segment_typecolumn datum new_value datum noprintcolumn 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'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, owner, tablespace_name,

Page 50: Oracle Db a Scripts One in All

segment_type, segment_name, count(extent_id) extent_id, sum(bytes) bytes from sys.dba_extents where substr(owner,1,10) not in ('sys')group by owner, tablespace_name, segment_type, segment_namehaving count(extent_id) > 3order by 1,2,3,4;

owner tablespace type name extents [bytes]---------- -------------------- ---------- ------------------------------ --------- ----------------dispatcher idx index pk_ssc_sms_ccbs 4 20,971,520 tbs_sccorder table sscorder 4 419,430,400 tbs_sccorder_idx index idx_sscorder_history_msisdn 4 419,430,400

sysadm tbs_sscms table sscms 4 2,076,172,288

*************************************************8). 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 bad 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_reads "physreads", 100 * round((b.consistent_gets + b.block_gets - b.physical_reads) / (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 nullorder by hitratio asc;

show sessions with bad buffer cache hit ratio in %

Page 51: Oracle Db a Scripts One in All

user sid consgets blockgets physreads hitratio------------ ---------- ---------- ---------- ---------- ----------sysadm 101 45719 6 38640 15.5dispatcher 111 466434 16 390966 16.2vp_link 95 94058 6 65802 30vp_link 75 94150 4 43350 54dispatcher 84 1288381 28 470437 63.5vp_link 40 436526 2 116192 73.4vp_link 90 437587 2 112440 74.3smh_link 109 1920356 1345626 799163 75.5sscsmsci 68 5 0 1 80dispatcher 94 52 8 9 85sys 115 58443 6811 6845 89.5vp_link 88 19 2 2 90.5vp_link 72 374313 998401 78614 94.3vp_link 89 373818 997023 78529 94.3vp_link 87 373435 995770 78406 94.3vp_link 97 373546 996162 78587 94.3vp_link 93 374399 998969 78478 94.3vp_link 80 7048 18880 1444 94.4vp_link 70 1813 4768 364 94.5vp_link 92 1851 4952 369 94.6vp_link 86 1870 4994 362 94.7mig_ota 91 1113 8 46 95.9vp_link 104 21 14 1 97.1vp_link 98 56 2 1 98.3vp_link 96 239 578 13 98.4dispatcher 110 1092370 3875255 59535 98.8sscsmh 105 59195 35151 1035 98.9tmh_link 77 842 2086 30 99vp_link 114 387838 853135 11724 99.1sscsmh 37 984588 543820 11500 99.2sscsmh 54 2318348 1304849 20178 99.4sscfsm 52 2938795 2408492 25907 99.5sscfsm 53 2933194 2403007 25963 99.5sscsmh 71 2835536 1592916 23697 99.5sscfsm 69 2938692 2407723 26245 99.5sscfsm 60 2934409 2404253 25990 99.5sscfsm 59 2936309 2406120 25942 99.5sscdsp 103 18518943 10226773 106777 99.6dispatcher 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 waits for some seconds-- and then tries to get the resource again. after-- a counter have reached the maximum, the routine-- exits.---- #############################################################################################

Page 52: Oracle Db a Scripts One in All

--create or replace procedure trytogetslot is gotit boolean := false; count number := 0;begin while (not gotit and not (count > 10)) loop begin -- try to get free slot, if ok, set gotit = true -- else exception will automatically fire. (insert code here) gotit := true; exception when others then gotit := false; dbms_lock.sleep(10); count := count + 1; end; end loop;end;/-- #############################################################################################---- %purpose: how to query a n x m relation using the union construct to avoid the ora-1417 error---- consider the following situation: we have employees and projects.---- an employee can be registered (work for) in 0, 1or more projects. for a certain 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 varchar2(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, constraint 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) references employee (emp_id));

Page 53: Oracle Db a Scripts One in All

insert into employee (emp_id,name) values (1,'allen');insert into employee (emp_id,name) values (2,'baker');insert into employee (emp_id,name) values (3,'ford');insert into employee (emp_id,name) values (4,'miller');insert into employee (emp_id,name) values (5,'scott');

insert into project (proj_id,name) values (1,'project 01');insert into project (proj_id,name) values (2,'project 02');insert into project (proj_id,name) values (3,'project 03');insert into project (proj_id,name) values (4,'project 04');insert into project (proj_id,name) values (5,'project 05');

insert into projalloc (proj_id,emp_id) values (1,1);insert into projalloc (proj_id,emp_id) values (1,2);insert into projalloc (proj_id,emp_id) values (1,3);insert into projalloc (proj_id,emp_id) values (2,2);insert into projalloc (proj_id,emp_id) values (2,5);insert into projalloc (proj_id,emp_id) values (3,3);insert into projalloc (proj_id,emp_id) values (4,3);commit;

select e.name employee,p.name name from employee e, projalloc pa, project pwhere 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 union construct to query the two special cases-- (all employees with no project assigned and-- all projects with no employees assigned).--select e.name employee,p.name project from employee e, projalloc pa, project pwhere e.emp_id = pa.emp_id and p.proj_id = pa.proj_idunionselect e.name, null from employee e, projalloc pawhere e.emp_id = pa.emp_id(+) and pa.emp_id is nullunionselect null, p.name project from project p, projalloc pawhere p.proj_id = pa.proj_id(+)and pa.proj_id is nullorder by 1;

employee project------------------------------ -----------allen project 01baker project 01baker project 02

Page 54: Oracle Db a Scripts One in All

ford project 01ford project 03ford project 04millerscott project 02 project 05-- #############################################################################################---- %purpose: how to reclaim unused_space from indexes and tables using dbms_space.unused_space---- before growing a datafile in a tablespace that shows on your-- space analysis reports, search for space that can be reclaimed-- from an object that was poorly sized initially. tables and indexes-- can be altered with a deallocate unused, thus reclaiming unused-- space above the high-water mark.---- example: alter table emp deallocate unused;---- this script prompts you for two pieces of information:---- 1. the type of segment to retrieve, (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_name. it is important to note that deallocating-- unused space became available with oracle version 7.3.---- #############################################################################################----accept type prompt "enter the type of segment to check (i=index, t=table): "accept ts_name prompt "enter the tablespace name that you wish to check: "set serveroutput onfeedback 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_block number; v_used number; v_owner varchar2(12); v_segment varchar2(80); v_type char(1);

cursor index_c is select owner, index_name from sys.dba_indexes

Page 55: Oracle Db a Scripts One in All

where tablespace_name = upper('&ts_name');

cursor table_c is select owner, table_name from sys.dba_tables where 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%found 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_block); -- dbms_output.put_line(chr(10)); dbms_output.put_line('index name = '||v_segment); dbms_output.put_line('total blocks = '||v_total_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_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_output.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_total_blocks); dbms_output.put_line('total bytes = '||v_total_bytes); dbms_output.put_line('unused blocks = '||v_unused_blocks);

Page 56: Oracle Db a Scripts One in All

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('. 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); dbms_output.put_line('last used block = '||v_last_block); fetch table_c into v_owner, 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/admin/help/helptbl.sql; exit;eof

$oracle_home/bin/svrmgrl << eof connect system/manager @$oracle_home/sqlplus/admin/help/helpindx.sql; exit;eof

$oracle_home/bin/sqlldr userid=system/manager control=$oracle_home/sqlplus/admin/help/plushelp.ctl$oracle_home/bin/sqlldr userid=system/manager control=$oracle_home/sqlplus/admin/help/plshelp.ctl$oracle_home/bin/sqlldr userid=system/manager control=$oracle_home/sqlplus/admin/help/sqlhelp.ctl-- #############################################################################################---- %purpose: monitor data access activities (full table and index scans, chained rows)

Page 57: Oracle Db a Scripts One in All

---- 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;

column statistic# form 999 head 'id'column na form a32 head 'statistic'column ria form 990.90 head 'row access via|index [%]'column rts form 990.90 head 'row access via|table scan [%]'column ra form 9999999990 head 'rows accessed'column pcr form 990.90 head 'chained|rows [%]'colum cl form 990.90 head 'cluster|length'

ttitle left 'monitor data access activities' skip 2

spool monitor_data_activites.log

select rpad (name, 32, '.') as na, value from v$sysstat where name like '%table scan%' or name like '%table fetch%' or name like '%cluster%';

ttitle off

select a.value + b.value as ra, a.value / (a.value + b.value) * 100.0 as ria, b.value / (a.value + b.value) * 100.0 as rts, c.value / (a.value + b.value) * 100.0 as pcr, e.value / d.value as cl from v$sysstat a, v$sysstat b, v$sysstat c, v$sysstat d, v$sysstat e where a.name = 'table fetch by rowid' and b.name = 'table scan rows gotten' and c.name = 'table fetch continued row' and d.name = 'cluster key scans' and e.name = 'cluster key scan block gets'/-- #############################################################################################--

Page 58: Oracle Db a Scripts One in All

-- %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: 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;

column na head 'statistic' format a29column nr_sess head '#users' format 9999column c1 head 'sum|[kbyte]' format 999990.90column c2 head 'avg|[kbyte]' format 999990.90column c3 head 'min|[kbyte]' format 999990.90column c4 head 'max|[kbyte]' format 999990.90

ttitle left 'monitor private sql areas and pl/sql space' skip 2

spool monitor_private_sql_areas.log

select 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 from v$sesstat a, v$statname b where a.statistic# = b.statistic# and (b.name like '%pga%' or b.name like '%uga%' or b.name like '%stored%') group by b.name/-- #############################################################################################---- %purpose: monitor sql*net communication activities---- use: needs oracle dba access----

Page 59: Oracle Db a Scripts One in All

#############################################################################################--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;

column na format a39 heading 'statistic'column value format 99999999990 heading 'value'

spool monitor_sqlnet_activities.log

select rpad (name, 39, '.') as na, value from v$sysstat where name like ('%sql*net%') order by na/

spool off;-- #############################################################################################---- %purpose: monitor sort activities (sorts in memory, sorts on disk)---- 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;

column statistic# format 999 heading 'id'column na format a32 heading 'parameter'column name format a32 heading 'statistik'column va format a8 heading 'value'column value format 9999999990

ttitle left 'monitor sort activities' skip 2

spool monitor_sort_activities.log

Page 60: Oracle Db a Scripts One in All

select rpad (name, 32, '.') as na, value as va from v$parameter where name like '%sort%'/

ttitle off

select name, value from v$sysstat where name in ('sorts (rows)', 'sorts (memory)', 'sorts (disk)')/

spool off;-- #############################################################################################---- %purpose: nls: show current nls database settings from sys.props$---- #############################################################################################--spool show_nls_current_settings.lstttitle left 'show current nls database settings' skip 2set feed offset pagesize 30000set linesize 200column name format a25column value$ 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.lstttitle left 'show valid nls parameters (territory, characterset)' skip 2set feed offset pagesize 30000set linesize 200

column parameter format a15column value format a15

Page 61: Oracle Db a Scripts One in All

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.lstset pause offset 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

column object_type format a25 wrap heading 'object|type'column object_name format a25 wrap heading 'object|name'column status format a8 heading 'status'column owner format a10 wrap heading 'owner'

select owner, object_name, object_type, status from dba_objectswhere status != 'valid';

spool off;-- #############################################################################################---- %purpose: performance enhancements with pl/sql dbms_sql bulk-operations instead of looping---- use: needs oracle dba access---- #############################################################################################--declare vcursor integer := dbms_sql.open_cursor; vcount integer;

Page 62: Oracle Db a Scripts One in All

vstatement varchar2(2000); vemps dbms_sql.varchar2_table;begin vstatement := 'update emp set sal = sal + 1' || ' where ename = :thisename'; vemps(1) := 'king'; vemps(2) := 'miller'; vemps(3) := 'huber'; vemps(4) := 'scott'; vemps(5) := 'adams';

begin dbms_sql.parse(vcursor,vstatement, dbms_sql.native); dbms_sql.bind_array(vcursor,'thisename',vemps); vcount := dbms_sql.execute(vcursor); dbms_sql.close_cursor(vcursor); dbms_output.put_line('vcount = ' || to_char(vcount)); end;end;-- #############################################################################################---- %purpose: recompile all invalid db-objetcs with dependency 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 referenced_object_id group by object_id) b where a.object_id = b.object_id(+) and status = 'invalid' and object_type in ('package body', 'package', 'function', 'procedure','trigger', 'view') order by order_number desc,object_type,object_name;spool off;

Page 63: Oracle Db a Scripts One in All

@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 bwhere a.object_id = b.object_id (+)and a.status = 'invalid'and a.object_type in ('package body','package','function','procedure','trigger','view')order by b.dlevel desc, a.object_type, a.object_name;--spool off;set heading 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_instance numeric,

Page 64: Oracle Db a Scripts One in All

object_type varchar2(30), optimizer varchar2(255), search_columns numeric, id numeric, parent_id numeric, position numeric, cost numeric, cardinality numeric, bytes 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---- paramters:-- 1: sequence name-- 2: table name-- 3: attribute name---- sample usage:-- @incseq.sql my_sequence my_table my_attribute------------------------------------------------------------------------------------set serveroutput on size 1000000;--declare 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) into curr from &2; while dummy < curr loop select &1..nextval into dummy from dual; end loop; -- dbms_output.put_line(', end=' || dummy); --end;/-- #############################################################################################

Page 65: Oracle Db a Scripts One in All

---- %purpose: send e-mail messages from pl/sql with oracle 8.1.6 using utl_tcp or 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 pl/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 server-based-- clients for the internet email protocol.---- this package requires that you install the jserver option---- author: frank naude ([email protected])---- #############################################################################################--create or replace procedure send_mail ( msg_from varchar2 := '[email protected]', -- must be a vaild e-mail address ! msg_to varchar2 := '[email protected]', -- must be a vaild e-mail address ! msg_subject varchar2 := 'message from pl/sql daemon', msg_text varchar2 := 'this message was automatically send by pl/sql daemon' )is conn utl_tcp.connection; rc integer; mailhost varchar2(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)); rc := utl_tcp.write_line(conn, 'helo '||mailhost); dbms_output.put_line(utl_tcp.get_line(conn, true)); rc := utl_tcp.write_line(conn, 'mail from: '||msg_from); dbms_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(utl_tcp.get_line(conn, true)); rc := utl_tcp.write_line(conn, 'subject: '||msg_subject); rc := utl_tcp.write_line(conn, ''); rc := utl_tcp.write_line(conn, msg_text); rc := utl_tcp.write_line(conn, '.'); -- end of message body with a "." dbms_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_connection(conn); -- close the connectionexception when others then raise_application_error(-20000, 'unable to send e-mail message from pl/sql procedure');end;

Page 66: Oracle Db a Scripts One in All

/show errors

-- examples:set serveroutput on

exec send_mail();exec send_mail(msg_to =>'[email protected]');exec send_mail(msg_to =>'[email protected]', msg_text=>'how to send e-mail from pl/sql');

create or replace procedure send_mail2 ( sender in varchar2, recipient in varchar2, message in varchar2)is mailhost varchar2(30) := 'rabbit.akadia.com'; smtp_error exception; mail_conn utl_tcp.connection; procedure smtp_command(command in varchar2, ok in varchar2 default '250') is response varchar2(3); rc integer; begin rc := utl_tcp.write_line(mail_conn, command); response := substr(utl_tcp.get_line(mail_conn), 1, 3); if (response <> ok) then raise smtp_error; end if; end;

begin mail_conn := utl_tcp.open_connection(mailhost, 25); smtp_command('helo ' || mailhost); smtp_command('mail from: ' || sender); smtp_command('rcpt to: ' || recipient); smtp_command('data', '354'); smtp_command(message); smtp_command('quit', '221'); utl_tcp.close_connection(mail_conn);exception when others then raise_application_error(-20000, 'unable to send e-mail message from pl/sql');end;/

exec send_mail2('[email protected]','[email protected]','test');

create or replace procedure send_mail3 (sender in varchar2, recipient in varchar2, message in varchar2)is mailhost varchar2(30) := 'rabbit.akadia.com'; mail_conn utl_smtp.connection;

Page 67: Oracle Db a Scripts One in All

begin mail_conn := utl_smtp.open_connection(mailhost, 25); utl_smtp.helo(mail_conn, mailhost); utl_smtp.mail(mail_conn, sender); utl_smtp.rcpt(mail_conn, recipient); utl_smtp.data(mail_conn, message); utl_smtp.quit(mail_conn);exception when others then raise_application_error(-20000, 'unable to send e-mail message from pl/sql');end;/

exec send_mail3('[email protected]','[email protected]','subject: test');

-- #############################################################################################---- %purpose: set private synonyms to schema of a connected oracle user---- use: each oracle user---- #############################################################################################--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;--promptprompt **** private synonyme auf waehlbares schema setzen *****promptprompt sie brauchen schreibrechte im aktuellen verzeichnis,prompt damit das sql-script gen_private_syn.sql generiertprompt werden kann. dieses wird (leider) nach der ausfuehrungprompt nicht automatisch geloescht, da sqlplus leider nichtprompt weiss wie man das macht ...promptprompt ********************************************************promptwhenever sqlerror exit sql.codeaccept schema_name char prompt 'enter schema (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;

Page 68: Oracle Db a Scripts One in All

--select 'create synonym '||table_name||' for &&schema_name'||'.'||table_name ||';' from all_tables where (upper(owner) like upper('%&&schema_name%') or upper(owner) like upper('&&schema_name'));--select 'create synonym '||sequence_name||' for &&schema_name'||'.'||sequence_name ||';' from all_sequences where (upper(sequence_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.sql;exit;-- #############################################################################################---- %purpose: show 'who owns what where' in the database---- #############################################################################################---- script to map tablespace names to database-- owners, and database owners to tablespaces.-- this will allow you to see who owns what where.-- 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 feed off;set pagesize 10000;set wrap off;set linesize 200;set heading on;set tab on;set echo off;set scan on;set verify off;

ttitle left 'output generated by: ' sql.user -skip -

Page 69: Oracle Db a Scripts One in All

skip -left 'who owns what where' -skip -left 'oracle version ' format a15 sql.release -skip 2set feed offset pagesize 10000break on owner on tablespace_namecolumn owner format a20 heading 'owner'column tablespace_name format a32 heading 'tablespace'column objects format a26 heading 'objects'

spool who_owns_what_where.lst;

select substr(owner,1,20) owner, substr(tablespace_name,1,32) tablespace_name, count(*) || ' tables' objectsfrom sys.dba_tablesgroup by substr(owner,1,20), substr(tablespace_name,1,32)unionselect substr(owner,1,20) owner, substr(tablespace_name,1,32) tablespace_name, count(*) || ' indexes' objectsfrom sys.dba_indexesgroup by substr(owner,1,20), substr(tablespace_name,1,32);clear columnsclear breaks

column tablespace_name format a32 heading 'tablespace'column owner 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' objectsfrom sys.dba_tablesgroup by substr(tablespace_name,1,32), substr(owner,1,20)unionselect substr(tablespace_name,1,32) tablespace_name, substr(owner,1,20) owner, count(*) || ' indexes' objects from sys.dba_indexesgroup by substr(tablespace_name,1,32), substr(owner,1,20);spool off;-- #############################################################################################---- %purpose: show 'who uses what objects' in the database

Page 70: Oracle Db a Scripts One in All

---- #############################################################################################---- 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$accesswhere owner != 'sys'order by owner;-- #############################################################################################---- %purpose: show buffer cache hit ratio in % for active instance since last startup---- #############################################################################################---- der buffer cache enth lt kopien der gelesenen daten blocks aus�-- den datenbankfiles. alle sessions teilen sich den buffer cache, der inhalt-- des buffer caches 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 einem cache hit.-- die tabelle v$sysstat zeigt die kumulierten werte seit die instance-- gestartet wurde. die physical reads seit dem instance startup verschlechtert-- 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 applikation: 89%---- #############################################################################################

Page 71: Oracle Db a Scripts One in All

--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 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 gets',value,0))))) * 100 "hit ratio in %" from v$sysstat a;-- #############################################################################################---- %purpose: show characteristics for system and other rollback segments---- #############################################################################################--spool show_rollback_segment.lstttitle left 'rollback-segment status' -skip 2set feed offset pagesize 10000column datum new_value datum noprintcolumn tablespace_name format a32 heading 'tablespace'column segment_name format a16 heading "rollback-segment"column status format a15 heading "status"column owner format a10 heading "owner"

select to_char(sysdate, 'mm/dd/yy') datum, segment_name, tablespace_name, status, ownerfrom sys.dba_rollback_segs;ttitle off;

select 'number of extents in system rollback segment (1): ' || count(*) "extents" from dba_extents where segment_name = 'system' and 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 rollback segment: ' || max_extents "max extents" from dba_rollback_segs

Page 72: Oracle Db a Scripts One in All

where segment_name = 'system';

ttitle left 'system rollback-segment status' -skip 2

select usn ,extents,rssize,hwmsize,optsize from v$rollstat where usn = 0;

spool off;

-- usn rollback segment number (0 = system rs)-- extents number of allocated extents.-- rssize total size of the rollback segment in bytes.-- hwmsize high water mark of rollback segment in bytes-- optsize optimal size of rollback segment (should be null).

-- #############################################################################################---- %purpose: show constraints of tabelles for a schema owner which 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.lstttitle off;column owner format a8 heading 'table|owner'column constraint_name format a30 heading 'constraint|name'column search_condition format a30 heading 'text'column table_name noprint new_value tabcolumn column_name format a15 heading 'column|name'column r_constraint_name format a30 heading 'reference|constraint'column status format 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 skip 2 -on constraint_name skip -

select c.constraint_name, i.search_condition,

Page 73: Oracle Db a Scripts One in All

c.table_name, c.column_name, i.r_constraint_name, i.statusfrom dba_cons_columns c, dba_constraints iwhere 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')order 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.release -skip -skip -left 'datafiles in data dictionary (view: dba_data_files)' -skip 2

set feed offset pagesize 10000

break on tablespace_namecolumn datum new_value datum noprintcolumn tablespace_name format a10 heading "tablespace"column file_name format a38 heading "datafile"column file_id format 99 heading "file-id"column 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, statusfrom dba_data_filesorder by file_id;

ttitle left 'datafiles in controlfile (table: v$dbfile)' -skip 2

set feed offset pagesize 10000

Page 74: Oracle Db a Scripts One in All

column name format a40 heading "datafile"column file# format 99 heading "file-id"select name,file# from v$dbfile;

ttitle left 'logfiles in controlfile (table: v$logfile)' -skip 2

set feed offset pagesize 10000column member format a40 heading "logfile"column group# format 99 heading "group-nr"column status format a10 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 sessions in den wartezustand versetzen. diese view kann-- verwendet werden, um rasch einen performance engpass herauszufinden.---- eine waiting time von 0 zeigt an, dass die session-- gerade auf einen event wartet. grosse wait times weisen auf 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 events' -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$session swhere w.sid = s.sidorder by 2,4;-- #############################################################################################---- %purpose: show db-files with heavy i/o (where are hotspots of reads und writes) ?

Page 75: Oracle Db a Scripts One in All

---- read_pct: prozent an gesamten reads, summe von read_pct = 100%-- write_pct: prozent 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) phys_wrts from v$filestat;

spool show_io_activity.lstttitle left 'disk i/o s by datafile' -skip 2

column name format a40 heading "filename"column phyrds format 999,999,999 heading "reads|number"column phywrts format 999,999,999 heading "writes|number"column read_pct format 999.99 heading "reads|in [%]"column write_pct format 999.99 heading "writes|in [%]"select name, phyrds, phyrds * 100 / trw.phys_reads read_pct, phywrts, phywrts * 100 / trw.phys_wrts write_pct from tot_read_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 onttitle off-- #############################################################################################---- %purpose: show dbms_jobs for all oracle users---- use: needs oracle dba access---- #############################################################################################--ttitle off;select substr(job,1,4) "job", substr(log_user,1,5) "user", substr(schema_user,1,5) "schema",

Page 76: Oracle Db a Scripts One in All

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", substr(failures,1,6) "failed", substr(what,1,20) "command" from dba_jobs;-- #############################################################################################---- %purpose: show data dictionary cache hit % for active instance since last startup---- #############################################################################################---- der data dictionary cache ist teil des shared pools. nach dem instance-- startup werden die data dictionary informationen ins memory geladen.-- nach einer gewissen betriebszeit sollte sich ein stabiler 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(gets))) * 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 left 'used space for each oracle user' -skip 2

set feed offset linesize 80set pagesize 5000

Page 77: Oracle Db a Scripts One in All

set underline '-'

break on owner skip 1 on tablespace_name on segment_typecolumn owner format a16 heading 'owner'column segment_type format a10 heading 'object'column tablespace_name format a26 heading 'tablespace'column bytes format 9,999,999,999 heading 'used space|[bytes]'column blocks format 999,999 heading 'used space|[blocks]'compute sum of bytes blocks on owner---- count space for each oracle object--select substr(owner,1,16) owner, substr(tablespace_name,1,26) tablespace_name, substr(segment_type,1,10) segment_type, sum(bytes) bytes, sum(blocks) blocksfrom sys.dba_extentsgroup by substr(owner,1,16), substr(tablespace_name,1,26), substr(segment_type,1,10)order by 1,2,3;clear breaksclear computesclear 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.lstttitle off

column trigger_name format a20 heading 'trigger|name'column trigger_type format a20 heading 'trigger|typ'column table_owner format a10 heading 'table|owner'column table_name noprint new_value tabcolumn table_name format a20 heading 'table|name'column triggering_event format a20 heading 'event'

Page 78: Oracle Db a Scripts One in All

column status format a8 heading 'status'

ttitle left 'trigger of tabelle: 'tab skip 2

break on table_name skip page -on owner skip 2 -on constraint_name skip -

select distinct table_owner, table_name, trigger_name, trigger_type, triggering_event, statusfrom dba_triggers where table_owner like upper('&user_namen');spool off;-- #############################################################################################---- %purpose: show file-i/o rate, system-i/o rate and throughput on all db-files---- #############################################################################################---- file i/o rate---- das file i/o rate diagramm zeigt die anzahl physical reads-- und writes pro sekunde der oracle datenbankfiles der gesamten instance.---- system i/o rate---- das system i/o rate diagramm zeigt die anzahl logischen und physischen-- reads sowie die anzahl block nderungen pro sekunde.�---- throughput---- das diagramm zeigt die anzahl user calls und transaktionen pro-- sekunde der gesamten 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;--ttitle left 'file i/o rate' -skip 2

Page 79: Oracle Db a Scripts One in All

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,'consistent gets', value,0))) "block gets+consistent gets", sum(decode(name,'db block changes', value,0)) "db block changes", sum(decode(name,'physical reads', value,0)) "physical reads" from v$sysstat;

ttitle left 'throughput' -skip 2

select sum(decode(name,'user commits', value,0)) "user commits", sum(decode(name,'user calls', value,0)) "user calls" from v$sysstat;-- #############################################################################################---- %purpose: show foreign-key refrences from / to oracle tables---- use: needs oracle dba access---- #############################################################################################--spool obj_dependencies.lstset feed offset pagesize 10000ttitle off

break on owner on referenced_type on referenced_name on type skip 1column datum new_value datum noprintcolumn owner format a10 heading 'object|owner'column name format a24 heading 'object|name'column type format a10 heading 'object|type'column referenced_name format a22 heading 'parent|name'column referenced_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) owner, substr(referenced_type,1,10) referenced_type, substr(referenced_name,1,22) referenced_name, substr(type,1,10) type, substr(name,1,24) namefrom dba_dependencieswhere owner not in ('sys','system')and referenced_type not in ('non-existent')order by 1,2,3,4,5,6;

spool off;

Page 80: Oracle Db a Scripts One in All

exit;-- #############################################################################################---- %purpose: show foreign-primarykey relations with foreign 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 keys that are missing indexes on-- the foreign key columns in the child table. if the 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 200;set heading on;set tab on;set scan on;set verify off;--spool show_foreign_keys.lstttitle off;column tab_owner format a10 heading "owner";column tab_name_fk format a15 heading "fk-table";column col_name_fk format a15 heading "fk-column";column tab_name_pk format a15 heading "pk-table";column col_name_pk format a15 heading "pk-column"--ttitle left 'foreign key listing' skip 2

break on tab_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_pkfrom dba_constraints a, dba_constraints b, dba_cons_columns c, dba_cons_columns dwhere a.r_constraint_name = b.constraint_name and a.constraint_type = 'r' and b.constraint_type = 'p' and a.r_owner=b.owner and a.constraint_name = c.constraint_name and b.constraint_name=d.constraint_name and a.owner = c.owner and a.table_name=c.table_name and b.owner = d.owner and a.owner not in ('sys','system') and b.table_name=d.table_name

Page 81: Oracle Db a Scripts One in All

order by 1,2,3;--select acc.owner||'-> '||acc.constraint_name||'('||acc.column_name ||'['||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','system') 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.constraint_type = 'r' minus select table_owner, table_name, column_name, column_position 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 onttitle off-- #############################################################################################---- %purpose: show free list hit ratio in % to verify database block contention---- #############################################################################################---- das diagramm free list hit % zeigt informationen zur datenblock� �-- contention. f r jedes segment unterh lt oracle ein oder mehrere freelists.� �-- freelists enthalten allozierte datenblocks f r diesen segment- extent mit�-- freiem platz f r INSerts. bei vielen concurrent inserts sind 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 (sum(value)-(sum(count)/2))/sum(value)*100 "gets" from v$waitstat w, v$sysstat s where w.class='free list' and s.name in ('db block gets', 'consistent gets');

Page 82: Oracle Db a Scripts One in All

select (sum(count) / (sum(value))) * 100 "misses"from v$waitstat w, v$sysstat swhere w.class='free list'and s.name in ('db block gets', 'consistent gets');-- #############################################################################################---- %purpose: show highwater mark of a table (choose table and schema owner)---- calculate highwatermark as follows or use package dbms_space.unused_space---- select blocks-- from dba_segments-- where owner = 'ppb'-- and segment_name = 'acm';---- select empty_blocks-- from dba_tables-- where owner = 'ppb'-- and table_name = 'acm';---- highwatermark := blocks - empty_blocks -1;---- beispiel: ausgangslage der tabelle test-- ----------------------------------------- total blocks = 440-- total bytes = 1802240-- unused blocks = 15-- unused bytes = 61440-- highwater mark = (440 - 15 - 1) = 424---- alter table test deallocate unused; /* ver ndert unused blocks und bytes */�---- total blocks = 425-- total bytes = 1740800-- unused blocks = 0-- unused bytes = 0-- highwater mark = (425 - 0 - 1) = 424---- delete from test; /* ver ndert hwm nicht, select count(*) geht lange ! */�---- total blocks = 425-- total bytes = 1740800-- unused blocks = 0-- unused bytes = 0-- highwater mark = (425 - 0 - 1) = 424---- truncate table test; /* reset der hwm, select count(*) geht schnell ! */---- total blocks = 20-- total bytes = 81920-- unused blocks = 19-- unused bytes = 77824-- highwater mark = (20 - 19 - 1) = 0----

Page 83: Oracle Db a Scripts One in All

#############################################################################################--set serveroutput on size 200000set echo offset feedback offset verify offset showmode offset linesize 500--accept l_user char prompt 'schemaowner: 'accept l_table char prompt 'tablename: '--declare op1 number; op2 number; op3 number; op4 number; op5 number; op6 number; op7 number; hwm number;begin dbms_space.unused_space(upper('&&l_user'),upper('&&l_table'),'table',op1,op2,op3,op4,op5,op6,op7); hwm := op1 - op3 - 1; dbms_output.put_line('--------------------------'); dbms_output.put_line('total blocks = '||op1); dbms_output.put_line('total bytes = '||op2); dbms_output.put_line('unused blocks = '||op3); dbms_output.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_hit_ratio.lst

ttitle 'user hit ratios' -

Page 84: Oracle Db a Scripts One in All

skip 2

column nl newline;column "hit ratio" format 999.99column "user session" format a15;set pagesize 999

select se.username||'('|| se.sid||')' "user session", 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',value, 0)) "phys reads", (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 gets',value, 0)) ) * 100 "hit ratio" from v$sesstat ss, v$statname sn, v$session sewhere ss.sid = se.sid and sn.statistic# = ss.statistic# and value != 0 and sn.name in ('db block gets', 'consistent gets', 'physical reads')group by se.username, se.sidhaving (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 gets',value, 0)) ) * 100 < 100;spool off;set feed on echo off termout on pages 24 verify onttitle off-- #############################################################################################---- %purpose: show i/o between db-server and clients over sql*net in bytes/s---- purpose: network bytes rate---- das diagramm network bytes rate zeigt die anzahl bytes / sekunde an� �-- daten, die vom datenbank server und seinen clients ber Sql*net�-- ausgetauscht werden.---- network i/o rate---- das diagramm network i/o rate zeigt die anzahl message� �-- packete / sekunde die vom datenbank server und seinen clients-- ber Sql*net ausgetauscht werden.�---- #############################################################################################--set feed off;set pagesize 10000;

Page 85: Oracle Db a Scripts One in All

set wrap off;set linesize 200;set heading on;set tab on;set scan on;set verify off;--ttitle left 'network bytes rate' -skip 2

column sum_value format 999,999,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 'bytes%sql*net%';

ttitle left 'network i/o rate' -skip 2

select sum(total_waits) total_waits from v$system_event where event like 'sql*net%';-- #############################################################################################---- %purpose: show initial, next, total extents, total blocks of db-objects---- #############################################################################################--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_object_storage_info.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) "type", 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 swhere s.segment_type in

Page 86: Oracle Db a Scripts One in All

('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.tablespace_name = t.tablespace_name (+) and s.owner = i.owner (+) and s.segment_name = 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 pages 24 verify onttitle off-- #############################################################################################---- %purpose: show indexes for a schema owner---- use: needs oracle dba access---- #############################################################################################--spool show_indexes.lstset pause offset feed off;set pagesize 10000;set wrap off;set linesize 200;set heading on;set tab on;set scan on;set verify off;

column index_name format a25 wrap heading 'index|name'column uni format a5 heading 'uniq-|ness'column tablespace_name format a10 wrap heading 'tablespace'column table_name noprint new_value tabcolumn column_name format a26 heading 'column|name'column table_owner format a10 heading 'table|owner'

ttitle left 'indexes of tabelle: 'tab skip 2

accept user_namen char prompt 'schema owner: '

break on table_name skip page -on table_owner skip 2 -on index_name skip -on uni -on tablespace_name

select i.table_owner, i.index_name, c.table_name,

Page 87: Oracle Db a Scripts One in All

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.table_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 shared pool of the instance---- #############################################################################################---- der library cache ist teil des shared 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 % aller sql-statements in geparster form im memory vorliegen m ssen.�-- ist dies nicht 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;set tab on;set scan on;set verify off;--ttitle left 'show library cache hit %' -skip 2

select (1-(sum(reloads)/sum(pins))) *100 "library cache hit %" from v$librarycache;-- #############################################################################################---- %purpose: show low-level locks (latches) on internal shared memory structures---- #############################################################################################

Page 88: Oracle Db a Scripts One in All

--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 '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$latchholder lh where l.latch#=ln.latch# and l.addr=lh.laddr(+) order by l.level#, l.latch#;-- #############################################################################################---- %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 memory 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;-- #############################################################################################---- %purpose: show number of logswitches per hour and day as a histogram---- use: needs oracle dba access---- #############################################################################################--

Page 89: Oracle Db a Scripts One in All

### version for oracle 7

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_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 'anzahl logswitches pro stunde' skip 2

select substr(time,1,5) day, to_char(sum(decode(substr(time,10,2),'00',1,0)),'99') "00", to_char(sum(decode(substr(time,10,2),'01',1,0)),'99') "01", to_char(sum(decode(substr(time,10,2),'02',1,0)),'99') "02", to_char(sum(decode(substr(time,10,2),'03',1,0)),'99') "03", to_char(sum(decode(substr(time,10,2),'04',1,0)),'99') "04", to_char(sum(decode(substr(time,10,2),'05',1,0)),'99') "05", to_char(sum(decode(substr(time,10,2),'06',1,0)),'99') "06", to_char(sum(decode(substr(time,10,2),'07',1,0)),'99') "07", to_char(sum(decode(substr(time,10,2),'08',1,0)),'99') "08", to_char(sum(decode(substr(time,10,2),'09',1,0)),'99') "09", to_char(sum(decode(substr(time,10,2),'10',1,0)),'99') "10", to_char(sum(decode(substr(time,10,2),'11',1,0)),'99') "11", to_char(sum(decode(substr(time,10,2),'12',1,0)),'99') "12", to_char(sum(decode(substr(time,10,2),'13',1,0)),'99') "13", to_char(sum(decode(substr(time,10,2),'14',1,0)),'99') "14", to_char(sum(decode(substr(time,10,2),'15',1,0)),'99') "15", to_char(sum(decode(substr(time,10,2),'16',1,0)),'99') "16", to_char(sum(decode(substr(time,10,2),'17',1,0)),'99') "17", to_char(sum(decode(substr(time,10,2),'18',1,0)),'99') "18", to_char(sum(decode(substr(time,10,2),'19',1,0)),'99') "19", to_char(sum(decode(substr(time,10,2),'20',1,0)),'99') "20", to_char(sum(decode(substr(time,10,2),'21',1,0)),'99') "21", to_char(sum(decode(substr(time,10,2),'22',1,0)),'99') "22", to_char(sum(decode(substr(time,10,2),'23',1,0)),'99') "23" from v$log_history group by substr(time,1,5)/spool off;

### version for oracle 8.1.x

set feed off;set pagesize 10000;set wrap off;set linesize 200;set heading on;

Page 90: Oracle Db a Scripts One in All

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, archived, 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') "01", 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: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,'ddmmyyyy:hh24:mi'),10,2),'07',1,0)),'99') "07", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'08',1,0)),'99') "08", to_char(sum(decode(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,'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: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:hh24:mi'),10,2),'17',1,0)),'99') "17", 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: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:mi'),10,2),'21'

Page 91: Oracle Db a Scripts One in All

,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_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'23',1,0)),'99') "23" from v$log_history group by to_char(first_time,'yyyy.mm.dd') /spool off;

### version for oracle 8.1.x with archived redologs

alter session set nls_date_format = 'dd.mm.yyyy:hh24:mi';

spool show_logswitches.lst

ttitle left 'redolog file status from v$log' skip 2

select group#, 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, to_char(sum(decode(substr(completion_time,12,2),'00',1,0)),'99') "00", to_char(sum(decode(substr(completion_time,12,2),'01',1,0)),'99') "01", to_char(sum(decode(substr(completion_time,12,2),'02',1,0)),'99') "02", to_char(sum(decode(substr(completion_time,12,2),'03',1,0)),'99') "03", to_char(sum(decode(substr(completion_time,12,2),'04',1,0)),'99') "04", to_char(sum(decode(substr(completion_time,12,2),'05',1,0)),'99') "05", to_char(sum(decode(substr(completion_time,12,2),'06',1,0)),'99') "06", to_char(sum(decode(substr(completion_time,12,2),'07',1,0)),'99') "07", to_char(sum(decode(substr(completion_time,12,2),'08',1,0)),'99') "08", to_char(sum(decode(substr(completion_time,12,2),'09',1,0)),'99') "09", to_char(sum(decode(substr(completion_time,12,2),'10',1,0)),'99') "10", to_char(sum(decode(substr(completion_time,12,2),'11',1,0)),'99') "11", to_char(sum(decode(substr(completion_time,12,2),'12',1,0)),'99') "12", to_char(sum(decode(substr(completion_time,12,2),'13',1,0)),'99') "13", to_char(sum(decode(substr(completion_time,12,2),'14',1,0)),'99') "14", to_char(sum(decode(substr(completion_time,12,2),'15',1,0)),'99') "15", to_char(sum(decode(substr(completion_time,12,2),'16',1,0)),'99') "16", to_char(sum(decode(substr(completion_time,12,2),'17',1,0)),'99') "17", to_char(sum(decode(substr(completion_time,12,2),'18',1,0)),'99') "18", to_char(sum(decode(substr(completion_time,12,2),'19',1,0)),'99') "19", to_char(sum(decode(substr(completion_time,12,2),'20',1,0)),'99') "20", to_char(sum(decode(substr(completion_time,12,2),'21',1,0)),'99') "21", to_char(sum(decode(substr(completion_time,12,2),'22',1,0)),'99') "22", to_char(sum(decode(substr(completion_time,12,2),'23',1,0)),'99') "23" from v$archived_log group by substr(completion_time,1,5)/spool off;

-- #############################################################################################--

Page 92: Oracle Db a Scripts One in All

-- %purpose: show number of objects (tab,ind,syn,vew,seq,prc,fun,pck,trg) for each oracle user---- use: needs oracle dba access---- #############################################################################################

---- version for oracle7/8--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 tab format 9999 heading "tab"column ind format 9999 heading "ind"column syn format 9999 heading "syn"column vew format 9999 heading "vew"column seq format 9999 heading "seq"column prc format 9999 heading "prc"column fun format 9999 heading "fun"column pck format 9999 heading "pck"column trg format 9999 heading "trg"column dep format 9999 heading "dep"

spool list_objects_by_user.lstttitle 'object count by user' -skip 2

select substr(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_users u where u.user_id = o.owner# (+) and o.type > 0 group by username;spool offset feed on echo off termout on pages 24 verify on

---- version for oracle8i--set feed off;

Page 93: Oracle Db a Scripts One in All

set pagesize 10000;set wrap off;set linesize 200;set heading on;set tab on;set scan on;set verify off;

column tab format 9999 heading "tab"column ind format 9999 heading "ind"column syn format 9999 heading "syn"column vew format 9999 heading "vew"column seq format 9999 heading "seq"column prc format 9999 heading "prc"column fun format 9999 heading "fun"column pck format 9999 heading "pck"column trg format 9999 heading "trg"column dep format 9999 heading "dep"

spool list_objects_by_user.lstttitle 'object count by user' -skip 2

select substr(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_users u where u.user_id = o.owner# (+) and o.type# > 0 group by username;spool offset feed on echo off termout on pages 24 verify on-- #############################################################################################---- %purpose: show number of rows per block for a table (only for oracle7 rowid)---- #############################################################################################--set echo offset feedback offset verify offset showmode offset pagesize 5000set linesize 500--accept l_table char prompt 'tablename: '

Page 94: Oracle Db a Scripts One in All

--spool show_rows_per_block_ora7.lstttitle left 'table rows per block' -skip 2--select substr(t.rowid,1,8) || '-' || substr(t.rowid,15,4) "block", count(*) "rows_per_block"from &&l_table twhere rownum < 2000group by substr(t.rowid,1,8) || '-' || substr(t.rowid,15,4);spool off;-- #############################################################################################---- %purpose: show number of transactions and other cursor statistics (commits, rollbacks, etc)---- 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;--column statistic# format 999 heading 'id'column na format a32 heading 'statistic'column ppe format 99990.90column nr_tx format 99999990column nr_recc format 99990.90

ttitle left 'monitor cursor activites' skip 2

spool cursor_activites.logset termout on

select rpad (name, 32, '.') as na, value from v$sysstat where name like '%cursor%' or name in ('parse count', 'execute count', 'user calls', 'user commits', 'user rollbacks', 'parse time cpu', 'parse time elapsed', 'recursive calls')/

Page 95: Oracle Db a Scripts One in All

ttitle left 'number of transactions' skip 2

select a.value + b.value as nr_tx from v$sysstat a, v$sysstat b where a.name = 'user commits' and b.name = 'user rollbacks'/

ttitle left 'recursive call per user call' skip 2

select c.value / d.value as nr_recc from v$sysstat c, v$sysstat d where c.name = 'recursive calls' and d.name = 'user calls'/

ttitle left 'parse per execute [%]' skip 2

select e.value / f.value * 100.0 as ppe from v$sysstat e, v$sysstat f where e.name = 'parse count' and f.name = 'execute count'/

spool offttitle off-- #############################################################################################---- %purpose: show number of physical reads and writes per sec for each db-file (i/o details)---- #############################################################################################--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 'file i/o rate details since last instance startup' -skip 2

select substr(name,1,30) "name",phyrds,phywrts,phyblkrd,phyblkwrt from v$dbfile df, v$filestat fs where df.file#=fs.file# order by name;--

Page 96: Oracle Db a Scripts One in All

#############################################################################################---- %purpose: show object privileges for schema owner which can 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_grants.lstttitle off

accept user_namen char prompt 'schema owner: '

column owner format a10 heading 'object|owner'column grantor format a22 heading 'user who|performed the grant'column grantee format a24 heading 'user/role to whom|access was granted'column privilege format a12 heading 'object|privilege'column table_name noprint new_value tab

ttitle left 'object grants on: 'tab skip 2

break on table_name skip page -on owner 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(grantee,1,24) grantee, substr(privilege,1,12) privilegefrom dba_tab_privswhere upper(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----

Page 97: Oracle Db a Scripts One in All

#############################################################################################--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;spool show_dictionary.lstselect substr(table_name,1,20) "table name", substr(comments,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.credit by 5000 in tablespace cre---- #############################################################################################--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_objects_no_next_extent.lst

ttitle 'show objects which cannot allocate the next extent' -skip 2

column owner format a10;column segment_name format a22;column segment_type format a10;column tablespace_name format a14;column next_extent format 999,999,999;

select seg.owner, seg.segment_name, seg.segment_type, seg.tablespace_name, t.next_extent from sys.dba_segments seg, sys.dba_tables twhere (seg.segment_type = 'table' and seg.segment_name = t.table_name

Page 98: Oracle Db a Scripts One in All

and seg.owner = t.owner and not exists (select tablespace_name from dba_free_space free where free.tablespace_name = t.tablespace_name and bytes >= t.next_extent ))unionselect 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 cwhere (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 ))unionselect seg.owner, seg.segment_name, seg.segment_type, seg.tablespace_name, decode (seg.segment_type, 'index', i.next_extent ) from sys.dba_segments seg, sys.dba_indexes iwhere (seg.segment_type = 'index' and seg.segment_name = i.index_name and seg.owner = i.owner and not exists (select tablespace_name from dba_free_space free where free.tablespace_name = i.tablespace_name and bytes >= i.next_extent ))unionselect seg.owner, seg.segment_name, seg.segment_type, seg.tablespace_name, decode (seg.segment_type, 'rollback', r.next_extent) from sys.dba_segments seg, sys.dba_rollback_segs rwhere (seg.segment_type = 'rollback' and seg.segment_name = r.segment_name and seg.owner = r.owner and not exists (select tablespace_name from dba_free_space free where free.tablespace_name = r.tablespace_name and bytes >= r.next_extent ))/ttitle 'segments that are sitting on the maximum extents allowable' -skip 2

select e.owner, e.segment_name, e.segment_type, count(*), avg(max_extents) from dba_extents e, dba_segments swhere e.segment_name = s.segment_name

Page 99: Oracle Db a Scripts One in All

and e.owner = s.ownergroup by e.owner, e.segment_name, e.segment_typehaving count(*) = avg(max_extents)/spool off;set feed on echo off termout on pages 24 verify onttitle off

-- #############################################################################################---- %purpose: show partition indexes (dba_ind_columns, dba_indexes)---- use: needs oracle dba access---- #############################################################################################--set feed off;set pagesize 100000;set wrap off;set linesize 200;set heading on;set tab on;set scan on;set verify off;

spool show_part_indexes.lstset pause off

column index_name format a25 wrap heading 'index|name'column uni format a5 heading 'uniq-|ness'column table_name noprint new_value tabcolumn column_name format a30 heading 'column|name'column table_owner format a10 heading 'table|owner'

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','no','???') 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.table_owner = c.table_owner and i.partitioned = 'yes'order by i.table_owner, c.table_name,

Page 100: Oracle Db a Scripts One in All

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: show partition tables and indexes (dba_tab_partitions)---- use: needs oracle dba access---- #############################################################################################--set feed off;set pagesize 100000;set wrap off;set linesize 200;set heading on;set tab on;set scan on;set verify off;--ttitle left 'show partition tables' -skip 2

set linesize 200set pagesize 500column table_name format a20 heading "table|name"column index_name format a20 heading "index|name"column partition_name format a20 heading "partition|name"column tablespace_name format a10 heading "tablespace"column partition_position format 999999 heading "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;

select index_name, partition_name, partition_position, tablespace_name from dba_ind_partitions order by index_name,partition_position;

Page 101: Oracle Db a Scripts One in All

spool offset feed on echo off termout on pages 24 verify on;ttitle off;-- #############################################################################################---- %purpose: show primary and foreign key relationsships---- use: needs oracle dba access---- #############################################################################################--spool show_fk_pk_relations.lstset feed offset pagesize 10000ttitle off--ttitle left 'primary and foreign key relationsships' skip 2set feed offset pagesize 10000--column datum new_value datum noprintcolumn for_owner format a5 heading 'table|owner'column pri_tsname format a10 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|column'break on for_owner skip 1

select a.owner for_owner, e.tablespace_name pri_tsname, a.table_name for_table, c.column_name for_col, b.table_name pri_table, d.column_name pri_colfrom dba_constraints a, dba_constraints b, dba_cons_columns c, dba_cons_columns d, dba_tables ewhere a.owner not in ('sys','system') and a.r_constraint_name = b.constraint_name and a.constraint_type = 'r' and b.constraint_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.table_name = e.table_nameorder by a.owner,a.table_name;--

Page 102: Oracle Db a Scripts One in All

#############################################################################################---- %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 verify off;--spool show_procedures.lstttitle offcolumn datum new_value datum noprintcolumn owner format a20 heading 'procedure|owner'column name format a20 heading 'procedure|name'column type format a20 heading 'procedure|type'

ttitle left 'defined procedures, functions, packages'skip 2

select distinct to_char(sysdate, 'mm/dd/yy') datum, substr(owner,1,12) owner, substr(name,1,27) name, substr(type,1,27) typefrom dba_sourcewhere 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 gr 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;

Page 103: Oracle Db a Scripts One in All

set linesize 200;set heading on;set tab on;set scan on;set verify off;--ttitle 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 requests', value,0)) "space requests", sum(decode(name,'redo synch writes', value,0)) "synch writes" from v$sysstat;-- #############################################################################################---- %purpose: show redo waits ('redo log space wait time', 'redo log space requests')---- #############################################################################################--col name format a30 justify l heading 'redo log buffer'col value format 99,999,990 justify 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 2set feed offset pagesize 10000break on grantee skip 1column datum new_value datum noprintcolumn grantee format a27 heading 'user or role|receiving the grant'

Page 104: Oracle Db a Scripts One in All

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, substr(granted_role,1,30) granted_role, substr(default_role,1,20) default_role, substr(admin_option,1,10) admin_optionfrom dba_role_privswhere 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 wert zu gross, so m ssen mehr rollbacksegmente�-- erstellt werden.---- rollback segment waits---- rollback segment waits k nnen einfach aus v$waitstat gelesen werden.�

-- waits auf undo header werden h ufig verringert, indem man weitere� � �-- rollback segmente erstellt.-- waits auf undo block werden verringert, indem man rollback segmente� �-- 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-- kontrolliert werden. extents und shrinks sollten keine auftreten, sonst-- muss der parameter optimal angepasst 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 'rollback nowait hit %' -skip 2

Page 105: Oracle Db a Scripts One in All

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 where stat.usn = name.usn and status = 'online';-- #############################################################################################---- %purpose: show sql-code of cpu-intensive oracle prozesses in the memory---- #############################################################################################---- tuning an application involves tuning the sql statements that are poorly-- designed. while tuning applications, it is important for a dba to find out which-- sql statements are consuming a large amount of cpu resources.-- after tracking down these statements, the dba can tune them to consume a less-- cpu, improving response timings considerably. the script will work only on unix-- operating systems.---- it displays the top 10 cpu-intensive oracle processes on the-- operating system with the first column giving the %cpu used, the second column-- unix pid, the third column user , the fourth column terminal, and the last-- column unix process. enter the unix pid at the prompt and it will display the-- statement belonging to that process.---- ps -eaf -o pcpu,pid,user,tty,comm | grep ora | grep -v \/sh | grep -v ora_ | sort -r | head -20---- #############################################################################--column username format a10column terminal format a9column sql_text format a30promptpromptpromptprompt enter the unix pid :accept pid--select a.username, a.terminal, a.program, b.sql_textfrom v$session a, v$sqlarea b, v$process cwhere (c.spid = '&pid' or a.process = '&pid')and a.paddr = c.addr

Page 106: Oracle Db a Scripts One in All

and a.sql_address = b.address/-- #############################################################################################---- %purpose: show sql-statements 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;set 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 distinct nvl(username,type) username,sid,sql_text from v$session, v$sqlarea where sql_hash_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 number of executions that took place on this object-- since iw was brought into the library cache.---- reads_per_run: number od disk-bytes reads per execution, if this is high, then-- the statement is i/o bound.---- i/o-intensive sql-statements in the memory (v$sqlarea)

Page 107: Oracle Db a Scripts One in All

---- total read-per-run disk-reads buffer-gets 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,858 181,282 57-- select msisdn, function, modif 1 12,087.0 12,087 25,602 53-- select msisdn, function, modif 1 12,031.0 12,031 25,599 53-- select msisdn, function, 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 needed 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-statement'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 format 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|ratio [%]'

ttitle left 'i/o-intensive sql-statements in the memory (v$sqlarea)' -skip 2

select sql_text, executions, round(disk_reads / executions, 2) reads_per_run, disk_reads, buffer_gets, round((buffer_gets - disk_reads) / buffer_gets, 2)*100 hit_ratiofrom v$sqlareawhere executions > 0and buffer_gets > 0

Page 108: Oracle Db a Scripts One in All

and (buffer_gets - disk_reads) / buffer_gets < 0.80order by 3 desc;-- #############################################################################################---- %purpose: shared pool minimium size calculator---- oracle server - enterprise edition 8.1.x - 10.1.x---- use: needs oracle dba access---- this script provides 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 for 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 15column shared_pool_size format 999,999,999column sum_obj_size format 999,999,999column sum_sql_size format 999,999,999column sum_user_size format 999,999,999column min_shared_pool format 999,999,999select 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 <> 'cursor'), (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 oracle-roles and db-user---- #############################################################################################--ttitle left 'output generated by: ' sql.user ' at: ' format a8 datum -

Page 109: Oracle Db a Scripts One in All

skip -skip -left 'system privileges on users and roles' -skip -left 'oracle version ' format a15 sql.release -skip 2set feed offset pagesize 10000break on grantee skip 1column datum new_value datum noprintcolumn grantee format a27 heading 'user or role|receiving the grant'column privilege format a40 heading 'system|privilege'column admin_option format a10 heading 'admin|option'

select to_char(sysdate, 'mm/dd/yy') datum, substr(grantee,1,27) grantee, substr(privilege,1,40) privilege, substr(admin_option,1,10) admin_optionfrom dba_sys_privsorder by 1,2,3;-- #############################################################################################---- %purpose: show segments with critical number of extents, soon reaching max_extents---- #############################################################################################--clear columns - breaks - computesset pagesize 100

column owner format a15column segment_name format a20column segment_type format a20

select owner,segment_name,segment_type,extents,max_extents from dba_segments where max_extents <= 10*(extents) and max_extents != 0;

column owner clearcolumn segment_name clearcolumn segment_type clear-- #############################################################################################---- %purpose: show sequences for schema owner---- #############################################################################################--

Page 110: Oracle Db a Scripts One in All

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_sequences.lstttitle off

column datum new_value datum noprintcolumn sequence_owner format a20 heading 'sequence|owner'column sequence_name noprint new_value sequencecolumn min_value format 99 heading 'minimal|value 'column max_value format 9.999eeee heading 'maximal |value 'column increment_by format 99 heading 'incr|by 'column last_number format 9999999 heading 'last |number 'column cache_size format 9999 heading 'cache|size 'column order_flag format a7 heading 'order ?'column cycle_flag format a7 heading 'cycle ?'

ttitle left 'properties for sequence: 'sequence skip 2

break on sequence_name skip page -on sequence_owner skip 2 -

select to_char(sysdate, 'mm/dd/yy') datum, substr(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_flagfrom dba_sequenceswhere 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)---- #############################################################################################

Page 111: Oracle Db a Scripts One in All

---- das diagramm no. of users logged on zeigt die anzahl concurrent� �-- users sessions, unabh nig davon ob sie nun aktiv sind oder nicht.�---- das diagramm no. of users running zeigt die users sessions,� �-- welche eine transaktion ausf hren.�---- das diagramm 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 locks warten m ssen.�---- #############################################################################################--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 off;--select sessions_current "users logged on" from v$license;--select count(*) "users running" from v$session_wait where wait_time!=0;--ttitle left 'users 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 swhere s.sid = w.sid and state = 'waiting' and event not like 'sql*net%' and event != 'client message' and event not like '%mon timer' and event != 'rdbms ipc message' and event != 'null event';--select count(*) "users waiting for locks" from v$session where lockwait is not null;-- #############################################################################################--

Page 112: Oracle Db a Scripts One in All

-- %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 bad 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_reads "physreads", 100 * round((b.consistent_gets + b.block_gets - b.physical_reads) / (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 nullorder by hitratio asc;-- #############################################################################################---- %purpose: show size of each 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 tables, but the size for the table itself.---- #############################################################################################--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_obyect_size.lstttitle off;

column owner format a8 heading 'object|owner'column name format a30 heading 'name'column type format a13 heading 'type'

Page 113: Oracle Db a Scripts One in All

column source_size format 99999999 heading 'source|size'column parsed_size format 99999999 heading 'parsed|size'column code_size format 99999999 heading 'code|size'column error_size format 99999999 heading 'error|size'

select owner, name, type, source_size, parsed_size, code_size, error_size from my_object_size where owner not in ('sys','system','public') order by owner,type/spool off;-- #############################################################################################---- %purpose: show startup time of the oracle instance (different for ora7 and ora8: v$instance)---- #############################################################################################---- instance startup-time for oracle-7--select to_char(to_date(d.value,'j'),'dd.mm.yyyy')||' '|| to_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 - seconds';---- instance startup-time for oracle-8--select to_char(startup_time,'dd.mm.yyyy:hh24:mi:ss') startup_time from v$instance;-- #############################################################################################---- %purpose: show statistics of connected sessions (pid, connection-type, username, logon-time)---- #############################################################################################--col osuser format a10 trunc heading "osuser as"col orauser format a10 trunccol machine format a10 trunccol sprogram format a15 trunccol process format a20 trunccol server format a3 trunccol sess_id format 9999col proc_id format a7--select s.osuser osuser, s.username orauser, s.machine machine,

Page 114: Oracle Db a Scripts One in All

s.program sprogram, p.program process, s.sid sess_id, p.spid proc_id, s.logon_time, s.server serverfrom v$session s, v$process pwhere s.paddr = p.addrand type != 'background'and p.username is not nullorder by 6/col osuser clearcol machine clearcol orauser clearttitle off-- #############################################################################################---- %purpose: show status for all objects (valid, invalid) of a schema owner---- show object of a user or wildcard incl. status-- (choice valid or invalid (default both)---- #############################################################################################--col user_name noprint new_value user_namecol date_time noprint new_value date_timecol owner format a13 trunccol object_name format a30col object_type format a8 trunc heading obj-typecol status format a7col last_ddl_time format a17promptprompt 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:promptaccept user_name char prompt "user name: "accept object_name char prompt "object name: "accept status char prompt "status: "set echo off termout off pause offselect upper(nvl('&&user_name','%')) user_name, to_char(sysdate,'dd.mm.yyyy hh24:mi') date_timefrom dual;set termout on;set feed on;set pagesize 10000;set wrap off;set linesize 200;set tab on;set verify offset timing offttitle left 'objects of user 'user_name' at 'date_time -

Page 115: Oracle Db a Scripts One in All

right sql.pno skip 2spool show_object_status.lstselect owner, object_name, decode(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 hh24:mi:ss') last_ddl_timefrom sys.dba_objectswhere 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 offpromptprompt show_object_status.lst has been spooledprompt-- #############################################################################################---- %purpose: show synonyms for all schmea 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 show_synonyms.lstbreak on table_owner skip 1column datum new_value datum noprintcolumn owner format a12 heading 'synonym|owner'column table_owner format a12 heading 'table|owner'column table_name format a26 heading 'table|name'column synonym_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_name, substr(synonym_name,1,26) synonym_name, substr(owner,1,12) ownerfrom dba_synonymswhere table_owner not in ('sys','system','dbsnmp');order by 1,2,3,4;spool off;--

Page 116: Oracle Db a Scripts One in All

#############################################################################################---- %purpose: show table grants for all schema owners---- use: each oracle user---- #############################################################################################--spool show_column_grants.lstttitle left 'show grants on table columns' skip 2set feed offset pagesize 10000

column owner noprint new_value owncolumn table_name format a20 heading 'object|name' trunccolumn column_name format a20 heading 'column|name' trunccolumn privilege format a9 heading 'privilege' trunccolumn grantee format a17 heading 'user/role to whom|access is granted' trunccolumn 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, privilegefrom dba_col_privsorder by owner, grantee, grantor, table_name/spool off;-- #############################################################################################---- %purpose: show table structure (column-name, datentyp, etc) for all schema-owners---- #############################################################################################--spool show_table_columns.lstset feed offset pagesize 10000ttitle off--column table_name noprint new_value tabcolumn owner format a10 heading 'table|owner'column column_name format a30 heading 'column|name'column data_type format a9 heading 'data|type'column nullable format a8 heading 'nulls ?'

Page 117: Oracle Db a Scripts One in All

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_columnswhere 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 schema-owners---- #############################################################################################--spool show_table_columns.lstset feed offset pagesize 10000ttitle off--column table_name noprint new_value tabcolumn owner format a10 heading 'table|owner'column column_name format a30 heading 'column|name'column data_type format a9 heading 'data|type'column nullable format a8 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,

Page 118: Oracle Db a Scripts One in All

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_columnswhere 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 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;

ttitle off;column owner format a5 heading 'table|owner'column t1 format a20 heading 'table|name'column comments format a100 heading 'comments'ttitle left 'table comments' skip 2

accept user_namen char prompt 'enter schema owner: '

break on ownerspool show_tab_col_comments.lst

select owner,table_name t1,comments from dba_tab_comments where owner like upper('&user_namen');

column t2 noprint new_value tabcolumn column_name format a20 heading 'column|name'ttitle off;clear break;

ttitle left 'column comments on tabelle: 'tab skip 2

break on t2 skip page -on owner skip 2 -

Page 119: Oracle Db a Scripts One in All

select owner,table_name t2,column_name,comments from dba_col_comments where owner like upper('&user_namen');

spool off;set feed on echo off termout on pages 24 verify on;ttitle off;-- #############################################################################################---- %purpose: show tablespace status information---- #############################################################################################--ttitle left 'output generated by: ' sql.user ' at: ' format a8 datum -skip -skip -left 'tablespace status' -skip -left 'oracle version ' format a15 sql.release -skip 2set feed offset pagesize 10000 column datum new_value datum noprintcolumn tablespace_name format a64 heading 'tablespace'column status format a15 heading "status"

select to_char(sysdate, 'mm/dd/yy') datum, tablespace_name, statusfrom sys.dba_tablespaces;-- #############################################################################################---- %purpose: show users with high cpu processing since instance startup---- #############################################################################################--set feed 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

Page 120: Oracle Db a Scripts One in All

column user_process format a10 heading "userprocess(sid)"column value format 999,999,999.99

select ss.username||'('||se.sid||')' user_process, value from v$session ss, v$sesstat se, v$statname sn where se.statistic# = sn.statistic# and name like '%cpu used by this session%' and se.sid = ss.sid and ss.username is not null order by substr(name,1,25), value desc/spool off;set feed on echo off termout on pages 24 verify onttitle off

-- #############################################################################################---- %purpose: show views for schmea-owner---- #############################################################################################--spool show_views.lstttitle left 'all database views' skip 2set feed offset pagesize 30000set linesize 200break on owner skip 1column owner format a5 heading 'view|owner'column view_name format a20 heading '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_lengthfrom dba_viewswhere owner not in ('sys','dbsnmp','system')order by 1,2,3;spool 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

Page 121: Oracle Db a Scripts One in All

set pagesize 200set feedback offcolumn owner format a15column object_name format a30 heading 'object'column object_id format 999999 heading "id#"column object_type format a15column status format a8ttitle left 'invalid objects found for ...'skip 2---- lists all invalid objects for a database--spool list_invalid_objects.lstset termout off--select owner, object_name, object_id, object_type, status from dba_objectswhere status != 'valid' and owner not in ('sys','system');--spool off---- create script which can be used to recompile-- all of the invalid objects--ttitle offset concat +spool compile_invalid_objects.sqlset concat .set feedback offset heading offset pagesize 999set verify off

select distinct 'sqlplus '||owner||'/'||owner||'<<eof'||chr(10)||'prompt compiling '||owner||' objects...'||chr(10)||'execute dbms_utility.compile_schema('||chr(39)||owner||chr(39)||');'||chr(10)||'show err;'||chr(10)||'quit'||chr(10)||'eof' from dba_objectswhere 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||' compile;'||chr(10)||'show errors view '||object_name||';'||chr(10)||'quit'||chr(10)||'eof' from dba_objectswhere status != 'valid' and object_type = 'view' and owner not in ('sys','system');

spool offset termout on

promptprompt list_invalid_objects.lst has been spooledprompt compile_invalid_objects.sql has been spooledprompt

Page 122: Oracle Db a Scripts One in All

-- #############################################################################################---- %purpose: show all privileges for a connected user through roles and direct---- show all privileges for a connected user over roles and-- direct. show all system- and object privileges as well.---- #############################################################################################--set feed offset pagesize 30000set linesize 200clear breaks columnsset pause offspool show_privileges_for_user.lis--ttitle left "currently active role(s) for user: " sql.user -skip 2column username format a22 heading 'user' trunccolumn role format a40 heading 'active|role' trunccolumn default_role format a7 heading 'default|role' trunccolumn admin_option format a7 heading 'admin|option' trunc--break on 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 2column username format a22 heading 'user' trunccolumn granted_role format a40 heading 'granted|role' trunccolumn default_role format a7 heading 'default|role' trunccolumn admin_option format a7 heading 'admin|option' trunc

select username,granted_role,default_role,admin_optionfrom user_role_privswhere not exists (select 'x' from session_roles where role = granted_role)unionselect 'all role(s) are active','','',''from dualwhere 0 = (select count('x') from user_role_privs where not exists (select 'x' from session_roles where role = granted_role))order by 1,2/--

Page 123: Oracle Db a Scripts One in All

ttitle left "sub-role(s) for user: " sql.user -skip 2column granted_role format a39 heading 'these role(s) are granted to ...' trunccolumn role format a39 heading '... these role(s)'

select granted_role,rolefrom role_role_privsunionselect 'no sub-role(s) found',''from dualwhere 0 = (select count('x') from role_role_privs)/--ttitle "system privileges through roles and direct for user: " sql.user -skip 2column role format a40 heading 'role' trunccolumn privilege format a30 heading 'system|privilege' trunccolumn admin_option format a7 heading 'admin|option' trunc--break on role skip 1

select role,privilege,admin_optionfrom role_sys_privsunionselect 'directly' role,privilege,admin_optionfrom user_sys_privsorder by 1,2/--ttitle "object privileges through roles and direct for user: " sql.user -skip 2column role format a20 heading 'role' trunccolumn owner format a17 heading 'object|owner' trunccolumn table_name format a20 heading 'object|name' trunccolumn privilege format a12 heading 'privilege' trunccolumn grantable format a6 heading 'admin|option' truncbreak on role on owner on table_name

select role, owner, table_name, privilege, grantablefrom role_tab_privswhere role in (select role from session_roles)and column_name is nullunionselect 'directly' role, owner, table_name, privilege, grantablefrom user_tab_privs_recdorder by 1,2,3,4/--ttitle "column privileges for user: " sql.user -skip 2column role format a16 heading 'role' trunccolumn owner format a10 heading 'object|owner' trunccolumn table_name format a20 heading 'object|name' trunccolumn column_name format a20 heading 'column|name' trunccolumn privilege format a10 heading 'privilege' trunc

Page 124: Oracle Db a Scripts One in All

select role, owner, table_name, column_name, privilege, grantablefrom role_tab_privswhere role in (select role from session_roles)and column_name is not nullunionselect 'directly' role, owner, table_name, column_name, privilege, grantablefrom user_col_privs_recdorder by 1,2,3,4/spool offclear breaks columnsttitle offpromptprompt listing created in "showpriv.lis"prompt-- #############################################################################################---- %purpose: show complete system statistic, e.g. full table scans, redolog infos 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 informationen gewonnen werden.�-- man beachte dass es sich bei diesen angaben immer 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---- index 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 rdo-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).

Page 125: Oracle Db a Scripts One in All

---- #############################################################################################--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 'system statistics' -skip 2

select s.name, s.value from v$sysstat sorder by s.name, s.value;-- #############################################################################################---- %purpose: show all schmea objects (tables,synonyms,views,sequences,indexes)---- use: jeder oracle user---- #############################################################################################--spool show_all_objects.lstset feed offset pagesize 10000ttitle off

column datum new_value datum noprintcolumn owner format a10 heading 'owner'column object_name format a38 heading 'object-|name'column object_type format a10 heading 'object-|type'column created format a10 heading 'created'column status format a8 heading 'status'

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(object_name,1,38) object_name, substr(created,1,11) created, substr(status,1,8) statusfrom dba_objectswhere substr(owner,1,10) not in ('sys','system','public','dbsnmp')order by 1,2,3,4;

Page 126: Oracle Db a Scripts One in All

spool off;exit;-- #############################################################################################---- %purpose: show block chaining (chained rows) with analyze table list chained rows---- use: needs oracle dba access---- #############################################################################################--set echo off termout offdrop table lst_chained_rows$tmp;set termout oncreate table lst_chained_rows$tmp(owner_name varchar2(30),table_name varchar2(30),cluster_name varchar2(30),head_rowid rowid,timestamp date);--accept user_namen char prompt 'username or %: 'accept tabellen_namen char prompt 'tablename or %: 'set feed off echo off termout off pages 0 verify off array 1--spool list_chained_rows.sqlselect 'analyze table '||owner||'.'||table_name, 'list chained rows into lst_chained_rows$tmp;'from sys.dba_tableswhere owner like upper('&user_namen')and table_name like upper('&tabellen_namen')order by owner, table_name;--spool offset feed on echo on termout on pages 66 verify on@list_chained_rows.sql--set echo offcolumn table_name format a30column owner_name format 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_freefrom sys.dba_tables t, lst_chained_rows$tmp cwhere t.owner = c.owner_nameand t.table_name = c.table_namegroup by owner_name, c.table_name, pct_free, num_rows

Page 127: Oracle Db a Scripts One in All

unionselect 'no block chaining',null,0,0,0from dualwhere 0 = ( select count(*) from lst_chained_rows$tmp where rownum = 1 )order by 1,2;spool offset feed on echo off termout on pages 24 verify onttitle offdrop table lst_chained_rows$tmp;-- #############################################################################################---- %purpose: show columns that have the same name but different characteristics---- this script lists columns that have the same name but-- different characteristics. they may cause problems-- when tables are joined on the columns or unexpected-- results are returned.---- #############################################################################################--accept user_namen char prompt 'schemaowner or wildcard : 'set feed off echo off termout on pages 5000 lines 500 verify off array 1--spool list_colnames_with_diff_length.lstttitle left 'columns with inconsistent data lengths' -skip 2

select substr(owner,1,10) "owner", column_name "colname", table_name||' '||data_type||'('|| decode(data_type, 'number', data_precision, data_length)||')' "characteristics" from all_tab_columns where (column_name, owner) in (select column_name, owner from all_tab_columns group by column_name, owner having min(decode(data_type, 'number', data_precision, data_length)) < max(decode(data_type, 'number', data_precision, data_length))) and owner like upper('&user_namen');spool off;set feed on echo off termout on pages 24 verify on;-- #############################################################################################---- %purpose: show detailled report of library cache usage in the shared pool of the instance---- #############################################################################################--

Page 128: Oracle Db a Scripts One in All

-- das diagramm library cache details zeigt detailinformationen� �-- des library cache im shared pool der instance. der library cache-- enth lt sql und pl/sql code in 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 linesize 200;set heading on;set tab on;set scan on;set verify off;--ttitle left 'library cache details' -skip 2

select namespace,gets,gethits, round(gethitratio*100) "ratio%", pins,pinhits,round(pinhitratio*100) "ratio%"from v$librarycache order by namespace;-- #############################################################################################---- %purpose: show fragmented objects (more than 3 extents)---- use: needs oracle dba access---- #############################################################################################--set feed offset pagesize 5000break on owner skip 1 on tablespace_name on segment_typecolumn datum new_value datum noprintcolumn 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'column extent_id format 999 heading 'number of|extents'column bytes format 999,999,999,999 heading 'size|[bytes]'---- looking for fragmented objects--select to_char(sysdate, 'mm/dd/yy') datum, owner, tablespace_name, segment_type, segment_name, count(extent_id) extent_id, sum(bytes) bytes

Page 129: Oracle Db a Scripts One in All

from sys.dba_extents where substr(owner,1,10) not in ('sys')group by owner, tablespace_name, segment_type, segment_namehaving count(extent_id) > 3order by 1,2,3,4;-- #############################################################################################---- %purpose: show free space in all datafiles and if autoextent is on---- #############################################################################################--clear columns - breaks - computesset pagesize 100

column file_name format a32column tablespace_name format a15column status format a3 trunccolumn t format 999,999.000 heading "total mb"column a format a4 heading "aext"column p format 990.00 heading "% free"

select df.file_name, df.tablespace_name, df. status, (df.bytes/1024000) t, (fs.s/df.bytes*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 sys.filext$ group by file#) ae where df.file_id = fs.file_id and ae.file#(+) = df.file_idorder by df.tablespace_name, df.file_id;

column file_name clearcolumn tablespace_name clearcolumn status clearcolumn t clearcolumn a clearcolumn p clearttitle off-- #############################################################################################

Page 130: Oracle Db a Scripts One in All

---- %purpose: show information about your current database account (who am i)---- #############################################################################################--set termout offset head offset termout on

select 'user: '|| user || ' on database ' || global_name, '(terminal='||userenv('terminal')|| ', session-id='||userenv('sessionid')||')'from global_name;

set head on feed on-- #############################################################################################---- %purpose: show installed database version and options with port specific infos---- 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;set serveroutput on;

ttitle left 'oracle version:' skip 2

select bannerfrom sys.v$version;

ttitle left 'installed options:' skip 2

select parameterfrom sys.v$optionwhere value = 'true';

ttitle left 'not installed options:' skip 2

select parameterfrom sys.v$optionwhere value <> 'true';

prompt

Page 131: Oracle Db a Scripts One in All

begin dbms_output.put_line('specific port information: '||dbms_utility.port_string);end;/prompt

set head on feed on

-- #############################################################################################---- %purpose: show last checkpoints in the file headers---- #############################################################################################--ttitle left 'output generated by: ' sql.user ' at: ' format a8 datum -skip -skip -left 'show last checkpoints in the file headers' -skip -left 'oracle version ' format a15 sql.release -skip 2set feed offset pagesize 10000set linesize 500break on grantee skip 1column datum new_value datum noprintcolumn file_nr format 999999 heading 'file#'column checkpoint_time format a20 heading 'checkpoint|time'column file_name format a59 heading '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 with nextval)---- use: needs sys access---- #############################################################################################--set feed off;set pagesize 10000;set wrap off;set linesize 200;set heading on;set tab on;set scan on;

Page 132: Oracle Db a Scripts One in All

set verify off;--spool show_nextval.lstttitle left 'shows next sequence number without incrementing it' skip 2--accept sequence_owner char prompt "sequence owner <% for all>: " default %accept sequence_name char prompt "sequence name <% for all>: " default %--col sequence_owner format a20 heading 'sequence|owner'col sequence_name format a25 heading 'sequence|name'col next_seq format 99999999 heading 'next|value'col cache format a25 heading 'cache'

select sequence_owner, sequence_name, next_seq, cachefrom (select sequence_owner, sequence_name, nextvalue next_seq, 'in cache' cache from v$_sequences where nextvalue is not null union select sequence_owner, sequence_name, highwater next_seq, 'created nocache' cache from v$_sequences where nextvalue is null union select sequence_owner, sequence_name, last_number next_seq, 'not in cache' cache from dba_sequences s where not exists (select sequence_owner, sequence_name from v$_sequences v where v.sequence_name = s.sequence_name and v.sequence_owner = s.sequence_owner))where sequence_owner like upper('&sequence_owner')and sequence_name like upper('&sequence_name')order by sequence_owner, sequence_name/undefine sequence_ownerundefine sequence_namecol sequence_owner clearcol sequence_name clearset verify onspool off

rem -------------------------------------------------------------------------rem shows actual dml-locks (incl. table-name)rem wait = yes are users waiting for a lockrem -----------------------------------------------------------------------rem--set pages 24 lines 80 feed on echo off termout on head oncolumn program format a80 trunccolumn locker format a10 trunccolumn t_owner format a10 trunccolumn object_name format a25 trunccolumn wait format a4ttitle "actual dml-locks (tm+tx)"-- select /*+ rule */ decode(l.request,0,'no','yes') wait,

Page 133: Oracle Db a Scripts One in All

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 decode(l.request,0,'no','yes') wait, s.osuser, s.process, s.username locker, '-', 'record(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 offcol program clearcol locker clearcol t_owner clearcol object_name clearcol wait clearrem -------------------------------------------------------------------------rem show users waiting for a lock, the locker and therem sql-command they are waiting for a lockrem osuser, schema and pids are shownrem -----------------------------------------------------------------------rem--set pages 24 lines 100 feed on echo off termout on head oncolumn os_locker format a15 trunccolumn os_waiter format a15 trunccolumn locker_schema format a15 trunccolumn waiter_schema format a15 trunccolumn waiter_pid format a10column locker_pid format a10column sql_text_waiter format a100 wrapcolumn database noprint new_value databasecolumn datum_zeit noprint new_value datum_zeitset termout off echo off feed offset termout onttitle center 'current lock-waits' skip 2-- select /*+ ordered no_merge(l_waiter) no_merge(l_locker) use_hash(l_locker)

Page 134: Oracle Db a Scripts One in All

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.osuser os_waiter, s_waiter.username waiter_schema, s_waiter.process waiter_pid, 'table lock (tm): '||u.name||'.'||o.name|| ' - mode held: '|| decode(l_locker.lmode, 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, 'exclusive', /* x */ '???: '||to_char(l_locker.lmode))|| ' / mode requested: '|| decode(l_waiter.request, 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, 'exclusive', /* x */ '???: '||to_char(l_waiter.request)) sql_text_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_waiter.request > 0 and l_locker.lmode > 0 and l_waiter.addr != l_locker.addr and l_waiter.id1 = o.obj# and u.user# = o.owner# union select /*+ ordered no_merge(l_waiter) 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)

Page 135: Oracle Db a Scripts One in All

*/ /* now the (usual) row-locks tx */ s_locker.osuser os_locker, s_locker.username 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_text_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 and l_waiter.type in ('tx') and s_locker.sid = l_locker.sid and l_locker.id1 = l_waiter.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 clear column waiter_schema clear column waiter_pid clear column locker_pid clear column sql_text_waiter clear column database clear column datum_zeit clearrem rem $header: utllockt.sql 21-jan-2003.16:21:56 bnnguyen exp $ locktree.sql rem rem copyright (c) 1989, 2003, oracle corporation. all rights reserved. rem namerem utllockt.sqlrem function - print out the lock wait-for graph in tree structured fashion.rem this is useful for diagnosing systems that are hung on locks.rem notesrem modifiedrem bnnguyen 01/21/03 - bug2166717rem pgreenwa 04/27/95 - fix column definitions for lock_holdersrem pgreenwa 04/26/95 - modify lock_holders query to use new dba_locks frem glumpkin 10/20/92 - renamed from locktree.sql rem jloaiza 05/24/91 - update for v7 rem rlim 04/29/91 - change char to varchar2 rem loaiza 11/01/89 - creationrem

/* print out the lock wait-for graph in a tree structured fashion.

Page 136: Oracle Db a Scripts One in All

* * 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, then it is waiting for that session. the session ids * printed at the left hand side 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 lock id1 lock id2 * ----------------- ---- ----------------- ----------------- -------- -------- * 8 none none none 0 0 * 9 tx share (s) exclusive (x) 65547 16 * 7 rw exclusive (x) s/row-x (ssx) 33554440 2 * 10 rw exclusive (x) s/row-x (ssx) 33554440 2 * * the lock information to the right of the session id describes the lock * 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 disadvantages. 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 script to get caught * in the lock problem it is trying to diagnose. two, if a session waits on * a lock held by more than one session (share lock) then the wait-for 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 lock, the lock they are waiting on, and the * sid of the session that holds the lock. * union * the sids of all session holding locks that someone is waiting on that * 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 */( waiting_session number, holding_session number, lock_type varchar2(26), mode_held varchar2(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;

Page 137: Oracle Db a Scripts One in All

/* 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 select w.session_id, h.session_id, w.lock_type, h.mode_held, w.mode_requested, w.lock_id1, w.lock_id2 from dba_locks_temp w, dba_locks_temp h where h.blocking_others = 'blocking' and h.mode_held != 'none' and h.mode_held != 'null' and w.mode_requested != '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_holders select holding_session, null, 'none', null, null, null, null from lock_holders minus select waiting_session, null, 'none', null, null, null, null from lock_holders;commit;

column waiting_session format a17;column lock_type format a17;column lock_id1 format a17;column 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,lock_id1,lock_id2

from lock_holdersconnect by prior waiting_session = holding_session 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 statements-- that have been recently executed. resource use is ranked by the

Page 138: Oracle Db a Scripts One in All

-- number of sga buffer gets, which is a good indicator of the work done.-- only statements that are still cached 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.buffer_gets, s.disk_reads, s.rows_processed, s.executions, substr(u.name,1,10) username, s.sql_textfrom v$sqlarea s, sys.user$ uwhere 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 the most resource intensive sql statements that have been recently executed---- displays a list of the most resource intensive sql statements-- 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.-- only statements that are still cached 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.buffer_gets, s.disk_reads,

Page 139: Oracle Db a Scripts One in All

s.rows_processed, s.executions, substr(u.name,1,10) username, s.sql_textfrom v$sqlarea s, sys.user$ uwhere 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 / database files---- use: needs oracle dba access---- #############################################################################################--clear bufferclear columnsclear breaksset linesize 500set pagesize 5000column a1 heading 'tablespace' format a15column a2 heading 'data file' format a45column a3 heading 'total|space [mb]' format 99999.99column a4 heading 'free|space [mb]' format 99999.99column a5 heading 'free|%' format 9999.99break on a1 on reportcompute sum of a3 on a1compute sum of a4 on a1compute sum of a3 on reportcompute sum of a4 on reportselect 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, substr(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

Page 140: Oracle Db a Scripts One in All

from sys.dba_free_space group by tablespace_name, file_id) bwhere a.file_id = b.file_id (+)order by 1, 2/-- #############################################################################################---- %purpose: show waiting sessions blocked through other sessions---- #############################################################################################---- die view row_lock_waits zeigt die wartenden sessions. dieses statement-- ist als view implementiert, es darf keine rows zur ckbringen, da sonst�-- ein user warten muss.---- create or replace 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 'waiting sessions' -skip 2

select * from row_lock_waits;-- #############################################################################################---- %purpose: show which users are accessing which rollback segments.--

Page 141: Oracle Db a Scripts One in All

-- 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_segment_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||')' "oracle user session", sq.sql_text from v$sqlarea sq, v$lock l, v$process p, v$session 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.address and s.sql_hash_value = sq.hash_value order by r.name/spool off;set feed on echo off termout on pages 24 verify onttitle off-- #############################################################################################---- %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---- #############################################################################################--

Page 142: Oracle Db a Scripts One in All

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.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||')' "oracle user session", sq.sql_text from v$sqlarea sq, v$lock l, v$process p, v$session 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.address and s.sql_hash_value = sq.hash_value order by r.name/spool off;set feed on echo off termout on pages 24 verify onttitle off-- #############################################################################################---- %purpose: show sid,serial#,pid,status,schema,osuser,box,prg,logon_time of logged on users---- #############################################################################################--set linesize 200 pagesize 1000 feed off;column "sid,serial#" format a12column "pid" format 999column "status" format a8column "schema" format a10column "osuser" format a10column "box" format a16column "prg" format a30--select '''' || s.sid || ','

Page 143: Oracle Db a Scripts One in All

|| s.serial# || ''';' "sid,serial#" , p.spid "pid" , s.status "status" , s.schemaname "schema" , s.osuser "osuser" , s.machine "box" , s.program "prg" , to_char(s.logon_time, 'dd.mm.yyyy hh24:mi') "logon_time" from v$session s, v$process pwhere s.paddr = p.addrorder by s.username/-- #############################################################################################---- %purpose: shows sql-statement for connected sid/srl# from v$sqltext---- #############################################################################################--set linesize 2000 trimspool onselect to_char(s.sid,'999') sid, to_char(s.serial#,'999999') srl#, substr(s.osuser,1,10) osusr, substr(s.schemaname,1,10) schema, substr(t.sql_text,1,100) sql_textfrom v$session s, v$sqltext twhere s.type <> 'background' and s.sql_address = t.address (+) and t.piece (+) = 0order 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 serial# as input into-- dbms_system.set_sql_trace_in_session to commence tracing the-- offending user.---- #############################################################################################

Page 144: Oracle Db a Scripts One in All

--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) from v$session ses2, v$sess_io sio2 where ses2.sid = sio2.sid and ses2.username not in ('system', 'sys'));-- #############################################################################################---- %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 serial# as input into-- dbms_system.set_sql_trace_in_session to commence tracing the-- offending user.---- #############################################################################################--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) from v$session ses2, v$sess_io sio2 where ses2.sid = sio2.sid and ses2.username not in ('system', 'sys'));-- #############################################################################################---- %purpose: solutions for the "mutation table problem" with delete cascade and cascade update---- #############################################################################################---- see http://www.akadia.com/services/ora_mutating_table_problems.html for the whole text.---- solution: using a temporary table---- if 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, resulting in-- a mutating table error, you may be able to use two triggers - an after row trigger that-- updates a temporary table, and an after statement trigger that updates the

Page 145: Oracle Db a Scripts One in All

original table-- with the values from the temporary table.---- in the next example "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;create 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_rbefore insert on cugfor each rowdeclare 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_type != 2) then raise_application_error(-20002, 'project- and community cugs must have a leading company'); end if;end;/

create or replace trigger au_rafter update of id_b on cugfor each rowbegin insert into cugtmp (id_b,type) values (:new.id_b,:new.type);end;/

create or replace trigger au_safter update of id_b on cugdeclare l_id_b number(12); l_typecd number(1); l_typeb number(1);

Page 146: Oracle Db a Scripts One in All

cursor cur_cugtmp is select id_b,type from cugtmp;begin open cur_cugtmp; loop fetch 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_typecd)); 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_application_error(-20002, 'project- and community cugs must have a leading company'); end if; end loop; close cur_cugtmp;end;/

insert into cug (id_cug,id_b,type) values (0,0,0); -- company 1insert into cug (id_cug,id_b,type) values (1,0,2); -- company 2insert into cug (id_cug,id_b,type) values (2,0,2); -- project 1insert into cug (id_cug,id_b,type) values (3,1,3); -- project 2insert into cug (id_cug,id_b,type) values (4,2,3); -- community 1insert into cug (id_cug,id_b,type) values (5,1,4); -- community 2insert 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 oracle dba access---- #############################################################################################--spool show_summary_invalid_objects.lst

Page 147: Oracle Db a Scripts One in All

set pause offset 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 'summary of invalid objects for user: ' sql.user -skip 2

column object_type format a25 wrap heading 'object|type'column status format a8 heading 'status'

select distinct (object_type), status, count(*)from dba_objectswhere status != 'valid'group by owner, object_type, status;-- #############################################################################################---- %purpose: try to set sql_trace on for another session / program---- use: sys-user---- #############################################################################################--create or replaceprocedure try_sql_trace_for_session (progname in varchar2) is---- try to enable sql_trace for progname---- example---- sql> set serveroutput 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 curs_get_sid is select sid,serial# from v$session where program like '%'||progname||'%';

begin while ncount = 0 loop for rec in curs_get_sid loop dbms_output.put_line('sid: '||rec.sid||' serial#: '||rec.serial#);

Page 148: Oracle Db a Scripts One in All

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');end;/-- #############################################################################################---- %purpose: tuning redologs und checkpoints (contention, waits, number/duration of checkpoints)---- #############################################################################################

1). redolog buffer contention-----------------------------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'780 2'534'627 0 0redo copy 33'818 27'694 357'613'861 150'511

misses/gets (must be < 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 redo log buffer----------------------------select name,value from v$sysstat where name = 'redo log space requests';

the value of 'redo log space requests' reflects the numberof times a user process waits for space in the redo log buffer.optimal is if the value is near 0 (oracle manual says this ...)

name value---------------------------------------------------------------- ----------redo log space requests 22641

4). number of checkpoints per hour----------------------------------set feed off;set pagesize 10000;set wrap off;

Page 149: Oracle Db a Scripts One in All

set linesize 200;set heading on;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, archived, 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') "01", 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: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,'ddmmyyyy:hh24:mi'),10,2),'07',1,0)),'99') "07", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'08',1,0)),'99') "08", to_char(sum(decode(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,'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: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:hh24:mi'),10,2),'17',1,0)),'99') "17", 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:mi'),10,2),'19',1,0)),'99') "19", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'20'

Page 150: Oracle Db a Scripts One in All

,1,0)),'99') "20", to_char(sum(decode(substr(to_char(first_time,'ddmmyyyy:hh24:mi'),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_char(first_time,'ddmmyyyy:hh24:mi'),10,2),'23',1,0)),'99') "23" from v$log_history group by to_char(first_time,'yyyy.mm.dd') /spool off;

day 00 01 02 03 04 05 06 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 007/08 0 0 0 0 0 0 0 0 0 0 0 5 0 4 1 0 1 0 0 0 0 0 0 007/12 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 0 0 007/13 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 007/14 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 007/15 1 0 0 0 0 0 0 0 0 0 0 0 2 1 0 0 1 2 2 0 0 0 0 007/16 0 0 10 10 15 11 5 0 0 0 0 0 2 5 5 4 5 7 6 6 7 4 4 407/17 2 2 1 3 4 6 9 10 11 11 12 12 11 11 12 11 11 12 12 9 9 10 12 907/18 12 9 10 10 8 8 9 10 9 8 9 10 10 11 10 11 10 10 11 10 11 9 10 1007/19 9 3 1 1 0 0 4 6 7 7 4 5 11 10 5 4 5 7 6 8 7 5 5 307/20 1 1 8 10 7 5 4 5 4 5 7 7 9 7 9 9 7 9 10 11 12 11 12 907/21 9 10 10 10 12 10 7 8 9 8 9 10 11 11 11 8 10 10 12 7 6 7 7 707/22 8 7 9 10 8 6 7 8 8 8 9 9 9 10 9 9 9 9 9 9 10 7 6 707/23 5 5 7 7 7 2 3 3 4 5 6 5 5 4 3 3 4 4 6 6 5 9 8 507/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 backgroundmon aug 2 16:37:36 1999thread 1 advanced to log sequence 2860 current log# 4 seq# 2860 mem# 0: /data/ota/db1/otasicap/redo/redootasicap04.logmon aug 2 16:43:31 1999

Page 151: Oracle Db a Scripts One in All

completed database checkpoint by background

==> 6 minutes

mon aug 2 16:45:15 1999beginning database checkpoint by backgroundmon aug 2 16:45:15 1999thread 1 advanced to log sequence 2861 current log# 5 seq# 2861 mem# 0: /data/ota/db1/otasicap/redo/redootasicap05.logmon aug 2 16:50:29 1999completed database checkpoint by background

==> 5.5 minutes

mon aug 2 16:51:50 1999beginning database checkpoint by backgroundmon aug 2 16:51:51 1999thread 1 advanced to log sequence 2862 current log# 6 seq# 2862 mem# 0: /data/ota/db1/otasicap/redo/redootasicap06.logmon aug 2 16:56:44 1999completed database checkpoint by background

==> 5.5 minutes-- #############################################################################################---- %purpose: which roles are currently enabled for my session ?---- 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 that can be concurrently enabled is limited by the-- initialization parameter max_enabled_roles. you can see which roles are-- currently enabled by examining the session_roles data dictionary view.---- #############################################################################################--select role from session_roles;---- you can check the db access in your application context using the following code construct.--declare hasaccess boolean := false; cursor cur_get_role is select role from session_roles;begin for role_rec in cur_get_role loop if (upper(role_rec.role) in ('admin','clerk')) then

Page 152: Oracle Db a Scripts One in All

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