isitdevops.com/databases

Useful computing notes
  • Archive
  • Home
  • Posts

Categories

  • Chef (Cat) (2)
  • Chef Cookbook Tutorials (8)
  • CHEF Full Tutorial (18)
  • Jernkins (Cat) (1)
  • Oracle (354)
    • Oracle 11g (Sect) (309)
      • Oracle 11.2 Notes (Cat) (18)
      • Oracle ASM (Cat) (1)
      • Oracle Data Guard Notes (Cat) (45)
      • Oracle DB and SQL performance analysis (Cat) (67)
      • Oracle DB Objects (tables, sql etc) (Cat) (56)
      • Oracle Exadata (Cat) (21)
      • Oracle Flashback Notes (Cat) (12)
      • Oracle Golden Gate (Cat) (11)
      • Oracle odds and ends (Cat) (39)
      • Oracle oui and dbca (Cat) (4)
      • Oracle RAC (Cat) (24)
      • Oracle Rman Notes (Cat) (10)
      • Oracle sql one liners (Cat) (1)
    • Oracle 12c (Sect) (45)
      • 12c Cloud control (Cat) (4)
      • 12c Cloud Control Agent (Cat) (2)
      • 12c General (Cat) (19)
      • 12c Performance (Cat) (4)
      • 12c rman (cat) (16)
  • SQL Server (Sect) (31)
    • MS SQL Server (Cat) (31)
  • Uncategorized (7)
  • Unix Notes (Sect) (50)
    • Configuration (Cat) (16)
    • Resource Management (Cat) (18)
    • Unix notes (Cat) (16)

Categories

  • Chef (Cat)
  • Chef Cookbook Tutorials
  • CHEF Full Tutorial
  • Jernkins (Cat)
  • Oracle
    • Oracle 11g (Sect)
      • Oracle 11.2 Notes (Cat)
      • Oracle ASM (Cat)
      • Oracle Data Guard Notes (Cat)
      • Oracle DB and SQL performance analysis (Cat)
      • Oracle DB Objects (tables, sql etc) (Cat)
      • Oracle Exadata (Cat)
      • Oracle Flashback Notes (Cat)
      • Oracle Golden Gate (Cat)
      • Oracle odds and ends (Cat)
      • Oracle oui and dbca (Cat)
      • Oracle RAC (Cat)
      • Oracle Rman Notes (Cat)
      • Oracle sql one liners (Cat)
    • Oracle 12c (Sect)
      • 12c Cloud control (Cat)
      • 12c Cloud Control Agent (Cat)
      • 12c General (Cat)
      • 12c Performance (Cat)
      • 12c rman (cat)
  • SQL Server (Sect)
    • MS SQL Server (Cat)
  • Uncategorized
  • Unix Notes (Sect)
    • Configuration (Cat)
    • Resource Management (Cat)
    • Unix notes (Cat)

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org

Create a physical standby database

on September 7, 2009 at 10:56 am
Posted In: Oracle Data Guard Notes (Cat)

ALTER DATABASE ARCHIVELOG;
ALTER DATABASE FORCE LOGGING;
ALTER DATABASE ADD STANDBY LOGFILE ‘..’ SIZE 50M;
SELECT GROUP#, TYPE, MEMBER FROM V$LOGFILE WHERE TYPE = ‘STANDBY’;
ALTER SYSTEM SET LOG_ARCHIVE_CONFIG = ‘DG_CONFIG=(db_unique_name_db, db_unique_name_sby)’;
SELECT * FROM V$DATAGUARD_CONFIG;
ALTER SYSTEM SET LOG_ARCHIVE_DEST_2=’SERVICE=stbydb, VALID_FOR=(ONLINE_LOGFILES, PRIMARY_ROLE) DB_UNIQUE_NAME=db_unique_name_sby’;
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=ENABLE;

#VALID_FOR = pairs of (logfiletype, role)
#log file types = ONLINE_LOGFILES / STANDBY_LOGFILES / ALL_LOGFILES
#role = PRIMARY_ROLE / STANDBY_ROLE / ALL_ROLES
#
# COMBINATION   PRIMARY  PHYSICAL LOGICAL
#ONLINE_LOGFILE, PRIMARY_ROLE Valid  Ignored  Ignored
#ONLINE_LOGFILE, STANDBY_ROLE…I….I…………V
#ONLINE_LOGFILE, ALL_ROLES ……..V….I…………V
#STANDBY_LOGFILE,STANDBY_ROLE I….V………..V
#STANDBY_LOGFILE,ALL_ROLES …….I….V………..V
#ALL_LOGFILES,PRIMARY_ROLE …….V….I…………I
#ALL_LOGFILES,STANDBY_ROLE …….I….V………..V
#ALL_LOGFILES,ALL_ROLES  …………V….V………..V
#
# n.b. both single and plural keywords are valid
#
# SYNC or ASYN, AFFIRN or NOAFFIRM
# ASYNC is default
# NOAFFIRM is default with ASYNC
# AFFIRM   is default with SYNC
#
# DB_FILE_NAME_CONVERT – do not use if OMF is in use.
# LOG_FILE_NAME_CONVERT – used to rename redo log file data – do not use if OMF is in use.
ALTER SYSTEM SET STANDBY_FILE_MANAGEMENT=AUTO;
#
COPY PRIMARY DB PASSWORD FILE TO THE STANDBY LOCATION.

CREATE AN INIT.ORA FILE CONTAINING JUST ONE LINE, “DB_NAME=stbyname”
CREATE THE AUDIT TRAIL IN $oracle_base/admin, i.e. $ORACLE_BASE/admin/dbname/adump
CREATE A DIRECTORY FOR THE ORACLE DATA FILES in $ORACLE_BASE/oradata
STARTUP STBY DB IN NOMOUNT
sql> startup nomount pfile=$initsby.ora;

ALTER SYSTEM SET FAL_CLIENT=’primary’;
ALTER SYSTEM SET FAL_SERVER=’stby’;

CREATE THE STANDBY
==================
$rman
rman> connect target sys/oracle
rman> connect auxiliary sys/oracle@pc00sby1
run {
allocate channel prmy1 type disk;
allocate channel prmy2 type disk;
allocate channel prmy3 type disk;
allocate channel prmy4 type disk;
allocate auxiliary channel stby type disk;
duplicate target database for standby from active database
spfile
parameter_value_convert ‘pc00prmy’, ‘pc00sby1’
set db_unique_name=’pc00sby1′
set db_file_name_convert=’/pc00prmy/’,’/pc00sby1/’
set log_file_name_convert=’/pc00prmy/’,’/pc00sby1/’
set control_files=’/u01/app/oracle/oradata/pc00sby1.ctl’
set log_archive_max_processes=’5′
set fal_client=’pc00sby1′
set fal_server=’pc00prmy’
set standby_file_management=’AUTO’
set log_archive_config=’DG_CONFIG=(pc00prmy,pc00sby1)’
set log_archive_dest_1=’service=pc00prmy ASYNC valid_for=(onlibe_logfile, primary_role) db_unique_name=pc00prmy’;
}
rman> exit

The RECOVERY_MODE column of V$ARCHIVE_DEST_STATUS contains “MANAGED REAL TIME APPLY” when real-time apply is in use.
If you define a DELAY ON A DESTINATION AND USE REAL-TIME APPLY, the delay is ignored.

To start real-time apply use “ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT;

set DB_LOST_WRITE_PROTECT init parameter to detect lost writes.
TYPICAL (on primary) only read/write tablespaces
FULL    (on primary) r/w and readonly tablespaces
TYPICAL or FULL on standby, performs detection during mrp
NONE    disables LOST WRITE detection

 Comment 

standby checks

on September 4, 2009 at 8:01 am
Posted In: Oracle Data Guard Notes (Cat)

select inst_id,thread#,sequence#,status
from gv$log
where status=’CURRENT’
order by inst_id,thread#,sequence#
/
select * from v$log where status = ‘current’;
select * from gv$managed_standby where process=’MRP0′;

select inst_id,status from gv$instance
/
select process, client_process, sequence#, status from gv$managed_standby
/
select protection_mode,protection_level,database_role as role,switchover_status from gv$database
/

 Comment 

session row lock contention

on September 4, 2009 at 7:57 am
Posted In: Oracle DB and SQL performance analysis (Cat)

select sid,sql_text
from v$session s, v$sql q
where sid in(select sid
from v$session where state in (‘WAITING’)
and wait_class !=’Idle’
and event=’enq: TX-row lock contention’
and (
q.sql_id=s.sql_id or
q.sql_id=s.prev_sql_id))

 Comment 

get protection level, db role (max availability performance protection) (Oracle)

on September 4, 2009 at 7:56 am
Posted In: Oracle Rman Notes (Cat)

select protection_mode, protection_level, database_role as role, switchover_status from v$database;

 Comment 

protection level max availability performance protection

on September 4, 2009 at 7:56 am
Posted In: Oracle Data Guard Notes (Cat)

select protection_mode,protection_level, database_role as role,
switchover_status
from v$database

 Comment 

data guard issue checking

on September 4, 2009 at 7:54 am
Posted In: Oracle Data Guard Notes (Cat)

— NAME: DG_phy_stby_diag.sql
— ————————————————————————
— AUTHOR:
–    Michael Smith – Oracle Support Services – DataServer Group
–    Copyright 2002, Oracle Corporation
— ————————————————————————
— PURPOSE:
–    This script is to be used to assist in collection information to help
–    troubeshoot Data Guard issues.
— ————————————————————————
— DISCLAIMER:
–    This script is provided for educational purposes only. It is NOT
–    supported by Oracle World Wide Technical Support.
–    The script has been tested and appears to work as intended.
–    You should always run new scripts on a test instance initially.
— ————————————————————————
— Script output is as follows:

set echo off
set feedback off
column timecol new_value timestamp
column spool_extension new_value suffix
select to_char(sysdate,’Mondd_hhmi’) timecol,
‘.out’ spool_extension from sys.dual;
column output new_value dbname
select value || ‘_’ output
from v$parameter where name = ‘db_name’;
spool dgdiag_phystby_&&dbname&Ãamp&&suffix
set lines 200
set pagesize 35
set trim on
set trims on
alter session set nls_date_format = ‘MON-DD-YYYY HH24:MI:SS’;
set feedback on
select to_char(sysdate) time from dual;

set echo on

—
— ARCHIVER can be  (STOPPED | STARTED | FAILED) FAILED means that the archiver failed
— to archive a — log last time, but will try again within 5 minutes. LOG_SWITCH_WAIT
— The ARCHIVE LOG/CLEAR LOG/CHECKPOINT event log switching is waiting for. Note that
— if ALTER SYSTEM SWITCH LOGFILE is hung, but there is room in the current online
— redo log, then value is NULL

column host_name format a20 tru
column version format a9 tru
select instance_name,host_name,version,archiver,log_switch_wait from v$instance;

— The following select will give us the generic information about how this standby is
— setup.  The database_role should be standby as that is what this script is intended
— to be ran on.  If protection_level is different than protection_mode then for some
— reason the mode listed in protection_mode experienced a need to downgrade.  Once the
— error condition has been corrected the protection_level should match the protection_mode
— after the next log switch.

column ROLE format a7 tru
select name,database_role,log_mode,controlfile_type,protection_mode,protection_level
from v$database;

— Force logging is not mandatory but is recommended.  Supplemental logging should be enabled
— on the standby if a logical standby is in the configuration. During normal
— operations it is acceptable for SWITCHOVER_STATUS to be SESSIONS ACTIVE or NOT ALLOWED.

column force_logging format a13 tru
column remote_archive format a14 tru
column dataguard_broker format a16 tru
select force_logging,remote_archive,supplemental_log_data_pk,supplemental_log_data_ui,
switchover_status,dataguard_broker from v$database;

— This query produces a list of all archive destinations and shows if they are enabled,
— what process is servicing that destination, if the destination is local or remote,
— and if remote what the current mount ID is. For a physical standby we should have at
— least one remote destination that points the primary set but it should be deferred.

COLUMN destination FORMAT A35 WRAP
column process format a7
column archiver format a8
column ID format 99

select dest_id “ID”,destination,status,target,
archiver,schedule,process,mountid
from v$archive_dest;

— If the protection mode of the standby is set to anything higher than max performance
— then we need to make sure the remote destination that points to the primary is set
— with the correct options else we will have issues during switchover.

select dest_id,process,transmit_mode,async_blocks,
net_timeout,delay_mins,reopen_secs,register,binding
from v$archive_dest;

— The following select will show any errors that occured the last time an attempt to
— archive to the destination was attempted.  If ERROR is blank and status is VALID then
— the archive completed correctly.

column error format a55 tru
select dest_id,status,error from v$archive_dest;

— Determine if any error conditions have been reached by querying thev$dataguard_status
— view (view only available in 9.2.0 and above):

column message format a80
select message, timestamp
from v$dataguard_status
where severity in (‘Error’,’Fatal’)
order by timestamp;

— The following query is ran to get the status of the SRL’s on the standby.  If the
— primary is archiving with the LGWR process and SRL’s are present (in the correct
— number and size) then we should see a group# active.

select group#,sequence#,bytes,used,archived,status from v$standby_log;

— The above SRL’s should match in number and in size with the ORL’s returned below:

select group#,thread#,sequence#,bytes,archived,status from v$log;

— Query v$managed_standby to see the status of processes involved in the
— configuration.

select process,status,client_process,sequence#,block#,active_agents,known_agents
from v$managed_standby;

— Verify that the last sequence# received and the last sequence# applied to standby
— database.

select al.thrd “Thread”, almax “Last Seq Received”, lhmax “Last Seq Applied”
from (select thread# thrd, max(sequence#) almax
from v$archived_log
where resetlogs_change#=(select resetlogs_change# from v$database)
group by thread#) al,
(select thread# thrd, max(sequence#) lhmax
from v$log_history
where resetlogs_change#=(select resetlogs_change# from v$database)
group by thread#) lh
where al.thrd = lh.thrd;

— The V$ARCHIVE_GAP fixed view on a physical standby database only returns the next
— gap that is currently blocking redo apply from continuing. After resolving the
— identified gap and starting redo apply, query the V$ARCHIVE_GAP fixed view again
— on the physical standby database to determine the next gap sequence, if there is
— one.

select * from v$archive_gap;

— Non-default init parameters.

set numwidth 5
column name format a30 tru
column value format a50 wra
select name, value
from v$parameter
where isdefault = ‘FALSE’;

spool off

 

 Comment 

list current archive logs

on September 4, 2009 at 7:52 am
Posted In: Oracle Data Guard Notes (Cat)

select inst_id,thread#,sequence#,status
from gv$log
where status=’CURRENT’
order by inst_id,thread#,sequence#

 Comment 

blocking session

on September 4, 2009 at 7:52 am
Posted In: Oracle DB and SQL performance analysis (Cat)

select blocking_session,sid,serial#,wait_class,seconds_in_wait
from v$session
where blocking_session is not null

 Comment 

select * from v$block_change_tracking

on September 4, 2009 at 7:51 am
Posted In: Oracle odds and ends (Cat)

select * from v$block_change_tracking

 Comment 

add standby log files

on September 4, 2009 at 7:46 am
Posted In: Oracle Data Guard Notes (Cat)

alter database add standby logfile thread 1 ‘+FRA’ size 100M;
alter database add standby logfile thread 1 ‘+FRA’ size 100M;
alter database add standby logfile thread 1 ‘+FRA’ size 100M;
alter database add standby logfile thread 1 ‘+FRA’ size 100M;
alter database add standby logfile thread 2 ‘+FRA’ size 100M;
alter database add standby logfile thread 2 ‘+FRA’ size 100M;
alter database add standby logfile thread 2 ‘+FRA’ size 100M;
alter database add standby logfile thread 2 ‘+FRA’ size 100M;
alter database add standby logfile thread 3 ‘+FRA’ size 100M;
alter database add standby logfile thread 3 ‘+FRA’ size 100M;
alter database add standby logfile thread 3 ‘+FRA’ size 100M;
alter database add standby logfile thread 3 ‘+FRA’ size 100M;

 Comment 

rman commands to backup a set of archivelogs as copy

on September 4, 2009 at 7:45 am
Posted In: Oracle Rman Notes (Cat)

#!/bin/ksh
THREAD=$1
SEQ1=$2
SEQ2=$3

###

rman target /;
backup as copy format ‘/oraback/al_%U’ archivelog sequence between $SEQ1 and $SEQ2 thread $THREAD ;

### or just backup an archivelog
backup as copy format ‘/oraback/al_%U’ archivelog sequence $SEQ1 thread $THREAD ;

 Comment 

rman copy of database

on September 4, 2009 at 7:38 am
Posted In: Oracle Rman Notes (Cat)

#!/bin/ksh
##########################################################################################
##########################################################################################
set -a

DB_NAME=$1
SITE=$2

###

# NB : Set to local values manually:

BACKUP_DAYS=4                     # Backupset Retention
ARCHLOG_DAYS=4                    # Archivelog retention
LOG=/u01/app/oracle/admin/${DB_NAME}${SITE}/backuplogs/${DB_NAME}_`date +%Y%m%d%H%M%S`.log

###

# Determine ORACLE_HOME and PATH:
#ORAENV_ASK=NO
#ORACLE_SID=$DB_NAME
#. oraenv
#unset ORAENV_ASK

# Determine ORACLE_SID from the instance that is running on this host:
ORACLE_SID=`ps -aef | grep ora_smon_ | grep $DB_NAME | awk -F”_” ‘{print $3}’|awk -F” ” ‘{print $1}’`

# Determine ORACLE_HOME and PATH
ORAENV_ASK=NO
. oraenv
unset ORAENV_ASK

echo “DB_NAME :         $DB_NAME” >> $LOG
echo “ORACLE_SID :              $ORACLE_SID” >> $LOG
echo “ORACLE_HOME :     $ORACLE_HOME” >> $LOG
echo “HOST :                    `hostname`” >> $LOG
echo “SITE :                    $SITE” >> $LOG
echo >> $LOG

NLS_DATE_FORMAT=”YYYY-MON-DD HH24:MI:SS”

$ORACLE_HOME/bin/rman target / > $LOG 2>&1

 set echo on;

 configure controlfile autobackup on;

 show all;

 recover device type disk copy of database with tag ‘Image_Copy’;

 backup as compressed backupset device type disk incremental level 1 for recover of copy with tag ‘Image_Copy’ tag ‘incr_update’ database;

 backup as compressed backupset device type disk archivelog until time ‘sysdate – ${ARCHLOG_DAYS}’ tag ‘incr_update’ delete all input;

 delete noprompt backup completed before ‘sysdate – ${BACKUP_DAYS}’ tag ‘incr_update’ device type disk;

 

 Comment 

contacts

on November 27, 2008 at 11:27 pm
Posted In: Oracle odds and ends (Cat)
CMC MARKETS
  Akash Gharu, 02030038333, a.gharu@cmcmarkets.com
  David Butler, 02030038499, 07786917604
  Dbas, 02030038666
  Andrew McKee, 02030038727
  Seka Mukassa, 07810827271
  CMC Markets UK PLC
  66 Prescot Street
  London
  E1 8HG

EADS
  Toby Challoner, 07989587692
  Dan O’Callaghan, 01633 757430
  Shaun Harding, 07766465837

EDS
  katharine.gifford
  katharine.gifford@eds.com
  01253
335203
  Mark Smith
  mark_smith_fr@hotmail.com

IBM 
  mike davies – ibm – 07843327839
  Michael Davies1 [michael.davies@uk.ibm.com],
  Michael Davies,
  Project Manager,
  IBM Global Business Services,
  Mobile: (44) (0)7843 327 839,
  Mobex: 270249
  chris.w.jackson@uk.ibm.com
  Keith ? 07967275530

akash
ORACLE
  Andrew Giddings, 07767817305

RAYTHEON
  chris.sheraton@trustedborders.co.uk

 
  Raytheon Systems Limited,
  Harman House
  1 George Street
  UxbridgeMiddx
  UB8 1QQ 

REUTERS
  Ashu Das 07905801337

Lorien, Agent, Daniel Harrison daniel.harrison@lorien.co.uk
Hyphen (Spring) Agent, Pau_Hal_HE05, lpool, thecontractorportal.com, ellie_taylor@hyphen.com

Dentist Philip Airdrie 01386 446693
Doctors Appointments 01386 853809
Dr Hughes, 01386853651
Plumber 01386443095

David Fenton, 01829759455, davef@loolee.org, david.fenton@credit-suisse.com
Imelda Eaves, imelda@eaves.co.uk
Karen and Colin Sibbald (niece, barbaras daughter), 62 Towers Rd, Childwall, Liverpool, L16 8NY
Catcid, 0058177692
Catpac 766937
Catrac 54466040
CMSJ admin, normal (no3)
CMSJ hallamp, Password01, hallampdb
CMS 1zwS4CYT
CMSW r5srPK9V
Quay, challam01, normal (no3)
RH hallamp2/hallamp2

Peter and Jane Edgworth, 07969322997, 8 Ash Close, Charlton Kings, Cheltenham, GL53 8PW
Luke Meadows, 07843655457
Zoe Meadows 07881867551
Home Hub, 01386427819

 Comment 

write to alert log and trace files

on November 11, 2008 at 4:26 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

——- WRITE TO ALERT AND TRACE FILE:
/*
exec dbms_system.ksdddt;
exec dbms_system.ksdwrt(3,’– Start Message –‘);
exec dbms_system.ksdwrt(3,’Testing Testing’);
exec dbms_system.ksdwrt(3,’– End Message –‘);
*/

——- WRITE TO ALERT AND TRACE FILE:
exec dbms_system.ksdddt;
exec dbms_system.ksdwrt(2,’– Start Message –‘);
exec dbms_system.ksdwrt(2,’Testing Testing’);
exec dbms_system.ksdwrt(2,’– End Message –‘);

 Comment 

system waits and events

on November 11, 2008 at 4:22 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

set pages 99
set lines 200

select INST_ID,SID,EVENT,WAIT_TIME,SECONDS_IN_WAIT,STATE FROM gv$session_wait where WAIT_CLASS <> ‘Idle’
order by 1,2
/

 

/*

select * from v$system_wait_class;

set lines 160
set numwidth 18
col class for a15
col event for a15
col total_waits for 999,999,999
col total_timeouts for 999,999,999
col time_waited for 999,999,999
col average_wait for 999,999,999
select b.wait_class,a.*,c.startup_time
from gv$system_event a,
     gv$event_name b,
     gv$instance c
where a.event=b.name
and (a.time_waited > 0 or a.average_wait > 0)
order by b.wait_class,a.time_waited asc;
*/

exit
=====

set pages 99
set lines 200

select  event, total_waits, total_timeouts, time_waited, average_wait, event_id
from gv$system_event
;

 

 Comment 

scn time

on November 11, 2008 at 4:20 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

set pages 999
select  scn
,       to_char(time_dp, ‘hh24:mi:ss dd/mm/yyyy’) time
from    smon_scn_time
order by scn
/

 Comment 

db version registry installed

on November 11, 2008 at 4:19 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

select comp_id, version, status, SUBSTR(comp_name,1,40) COMP_NAME from dba_registry;

 Comment 

flashback and recovery area information (Oracle 11g)

on November 11, 2008 at 4:18 pm
Posted In: Oracle Flashback Notes (Cat)

select * from v$flash_recovery_area_usage;

show parameter flash
show parameter db_recovery

select flashback_on from v$database;

 

select (100-sum(percent_space_used)) SPACE_REMAINING_PERCENTAGE from v$flash_recovery_area_usage;

 

select ((p.value/(1048576*1024))*f.space_USED_percentage) GB_USED
from
(select (sum(percent_space_used)/100) SPACE_USED_PERCENTAGE from v$flash_recovery_area_usage) f,
v$parameter p
where p.name=’db_recovery_file_dest_size’;

select ((p.value/(1048576*1024))*f.space_remaining_percentage) GB_REMAINING
from
(select 1-(sum((percent_space_used))/100) SPACE_REMAINING_PERCENTAGE from v$flash_recovery_area_usage) f,
v$parameter p
where p.name=’db_recovery_file_dest_size’;

select ((p.value/(1048576*1024))*f.space_reclaimable_percentage) GB_RECLAIMABLE
from
(select (sum((percent_space_reclaimable))/100) SPACE_RECLAIMABLE_PERCENTAGE from v$flash_recovery_area_usage) f,
v$parameter p
where p.name=’db_recovery_file_dest_size’;

 

select  oldest_flashback_scn scn
,       to_char(oldest_flashback_time, ‘hh24:mi:ss dd/mm/yyyy’) oldest_time
from    v$flashback_database_log
/

exit

 Comment 

open cursors

on November 11, 2008 at 4:17 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

set pages 200
set lines 150
col program format A30

–select * from gv$sysstat where name = ‘opened cursors current’;

select substr(a.sid,1,10) sid,
substr(nvl(b.program,machine),1,30) program,
count(*) CNT, b.inst_id
from gv$open_cursor a, gv$session b
where a.saddr=b.saddr
group by b.inst_id,substr(a.sid,1,10),
substr(nvl(b.program,machine),1,30)
order by 3 asc
;

accept SIDIN  number prompt ” Enter SID to acquire open cursors for: “

/*
select sql_text, inst_id, user_name from gv$open_cursor where SID=
(
select sid from (
select substr(a.sid,1,10) sid,
substr(nvl(b.program,machine),1,30) program,
count(*) CNT
from gv$open_cursor a, gv$session b
where a.saddr=b.saddr
group by substr(a.sid,1,10),
substr(nvl(b.program,machine),1,30)
order by 3 asc)
where rownum = 1
)
 ;
*/

 

select sql_text, inst_id, user_name from gv$open_cursor where SID=&SIDIN
 ;

/*
QL> desc gv$open_cursor
 Name                                                                                Null?    Type
 ———————————————————————————– ——– ——————————————————–
 INST_ID                                                                                      NUMBER
 SADDR                                                                                        RAW(8)
 SID                                                                                          NUMBER
 USER_NAME                                                                                    VARCHAR2(30)
 ADDRESS                                                                                      RAW(8)
 HASH_VALUE                                                                                   NUMBER
 SQL_ID                                                                                       VARCHAR2(13)
 SQL_TEXT                                                                                     VARCHAR2(60)

–select sql_text, inst_id, user_name from gv$open_cursor;
*/

exit

 Comment 

schema stats

on November 11, 2008 at 4:15 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

exec dbms_stats.gather_schema_stats(ownname=>’GARY’,GRANULARITY=>’ALL’,DEGREE=>4,CASCADE=>TRUE,OPTIONS=>’GATHER’);

 Comment 

instance load across rac

on November 11, 2008 at 4:10 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

select service_name,
instance_name,
elapsedpercall service_time,
cpupercall cpu_time,
dbtimepercall db_time,
callspersec throughput
from gv$instance gvi,
gv$active_services gvas,
gv$servicemetric gvsm
where gvas.inst_id=gvsm.inst_id
and gvas.name_hash=gvsm.service_name_hash
and gvi.inst_id=gvsm.inst_id
and gvsm.group_id=10
order by
service_name,
gvi.inst_id;

 Comment 

sql to get flashback area information (Oracle 11g)

on November 11, 2008 at 4:06 pm
Posted In: Oracle Flashback Notes (Cat)

select * from v$flash_recovery_area_usage;

show parameter flash
show parameter db_recovery

select flashback_on from v$database;

 

select (100-sum(percent_space_used)) SPACE_REMAINING_PERCENTAGE from v$flash_recovery_area_usage;

 

select ((p.value/(1048576*1024))*f.space_USED_percentage) GB_USED
from
(select (sum(percent_space_used)/100) SPACE_USED_PERCENTAGE from v$flash_recovery_area_usage) f,
v$parameter p
where p.name=’db_recovery_file_dest_size’;

select ((p.value/(1048576*1024))*f.space_remaining_percentage) GB_REMAINING
from
(select 1-(sum((percent_space_used))/100) SPACE_REMAINING_PERCENTAGE from v$flash_recovery_area_usage) f,
v$parameter p
where p.name=’db_recovery_file_dest_size’;

select ((p.value/(1048576*1024))*f.space_reclaimable_percentage) GB_RECLAIMABLE
from
(select (sum((percent_space_reclaimable))/100) SPACE_RECLAIMABLE_PERCENTAGE from v$flash_recovery_area_usage) f,
v$parameter p
where p.name=’db_recovery_file_dest_size’;

 

select  oldest_flashback_scn scn
,       to_char(oldest_flashback_time, ‘hh24:mi:ss dd/mm/yyyy’) oldest_time
from    v$flashback_database_log
/

exit

 Comment 

Configure audit trail

on November 11, 2008 at 4:01 pm
Posted In: Oracle odds and ends (Cat)

–alter system set audit_syslog_level=’DB, EXTENDED’ scope=spfile sid=’*’;
alter system set audit_trail=DB, EXTENDED scope=spfile sid=’*’;

ALTER SYSTEM SET audit_sys_operations=TRUE
COMMENT=’Begin auditing SYS’
SCOPE=spfile SID=’*’;

ALTER SYSTEM SET audit_trail=xml,extended
COMMENT=’enables database auditing and prints all columns of the audit trail, including SqlText and SqlBind values’
SCOPE=spfile SID=’*’;

alter system reset audit_syslog_level scope=spfile sid=’*’;

alter system set audit_syslog_level=” scope=spfile sid=’*’;
alter system set audit_trail=’NONE’ scope=spfile sid=’*’;

 

 Comment 

sessions waiting

on November 11, 2008 at 4:00 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

set pages 99
set lines 200

select session_id, event, count(*), sum(time_waited)
from gv$active_session_history
where session_state=’WAITING’
and time_waited>0
and sample_time >=(sysdate-&MinutesBack/(24*60))
group by session_id,event;

 

 Comment 

global cache gc latency

on November 11, 2008 at 3:58 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

 

col name format a45
select name,phyrds,phywrts,avgiotim
from v$datafile df,
v$filestat fs
where df.file#=fs.file#;
/*

Oracle recommends that the avg latency of a consitent block request shoudl typically be about 15ms depending on the system configuration and volume.  The average latency of a consitent blcok request is the average latency of a consitent=read request round trip from the requesting instance to the holding instance and back to the requesting instance.

*/

 

set numwidth 20
set pages 150
set lines 100

column “AVG CR BLOCK RECEIVE TIME (ms)” format 9999999.9
select
b1.inst_id,
b2.value “GCS CR BLOCKS RECEIVED”,
b1.value “GCS CR BLOCK RECEIVE TIME”,
((b1.value/b2.value)*10) “AVG CR BLOCK RECEIVE TIME (ms)”
from gv$sysstat b1,
gv$sysstat b2
where b1.name = ‘gc cr block receive time’
and b2.name = ‘gc cr blocks received’
and b1.inst_id = b2.inst_id;

 

/*
current reads:

average time to build a consistent read block is calculated as follows
gc cr block build time/gc cr blocks served

average time spent waiting for a redo log flush is calcuated as follows:
gc cr block flush time/gc cr blocks served

average time to send a completed block is calculated as follows:
gc cr block send time/gc cr blocks served

the followign query can be used to calculate the average LMS service time for consitent block reads:

 

FYI
the difference between the average latency time and the sum of the average build, flush, and send times represents the time spent in the LMS service and the time spent transmitting the meassages across the interconnect.

*/

select
average_latency as “Average Latency”,
average_build_time as “Average Build Time”,
average_flush_time as “Average Flush Time”,
average_send_time as “Average Send Time”,
average_latency – average_build_time – average_flush_time – average_send_time
as “Average LMS Service Time”
from
(
select
(gc_cr_block_receive_time * 10) / gc_cr_blocks_received as average_latency,
(gc_cr_block_build_time * 10) / gc_cr_blocks_served as average_build_time,
(gc_cr_block_flush_time * 10) / gc_cr_blocks_served as average_flush_time,
(gc_cr_block_send_time * 10) / gc_cr_blocks_served as average_send_time
from
(
select value as gc_cr_block_receive_time from v$sysstat
where name = ‘gc cr block receive time’
),
(
select value as gc_cr_blocks_received from v$sysstat
where name = ‘gc cr blocks received’
),
(
select value as gc_cr_block_build_time from v$sysstat
where name = ‘gc cr block build time’
),
(
select value as gc_cr_block_flush_time from v$sysstat
where name = ‘gc cr block flush time’
),
(
select value as gc_cr_block_send_time from v$sysstat
where name = ‘gc cr block send time’
),
(
select value as gc_cr_blocks_served from v$sysstat
where name = ‘gc cr blocks served’
)
);

/*
current blocks

average latency involved in processing requests for current blocks using the following:

*/

select
gc_current_block_receive_time as “Receive Time”,
gc_current_blocks_received as “Blocks Received”,
(gc_current_block_receive_time * 10) / gc_current_blocks_received as “Average (MS)”
from
(
select value as gc_current_block_receive_time from v$sysstat
where name = ‘gc current block receive time’
),
(
select value as gc_current_blocks_received
from v$sysstat
where name = ‘gc current blocks received’
);

/*
amount of overall latency that can be attributed to the LMS process using the following:

average LMS Service time = average latency – average time to pin current blocks – avg time to wait for log flush – average time to send completed blocsk

*/

 

select
average_latency as “Average Latency”,
average_pin_time as “Average Pin Time”,
average_flush_time as “Average Flush Time”,
average_send_time as “Average Send Time”,
average_latency – average_pin_time – average_flush_time – average_send_time
as “Average LMS Service Time”
from
(
select
(gc_current_block_receive_time * 10) / gc_current_blocks_received as average_latency,
(gc_current_block_pin_time * 10) / gc_current_blocks_served as average_pin_time,
(gc_current_block_flush_time * 10) / gc_current_blocks_served as average_flush_time,
(gc_current_block_send_time * 10) / gc_current_blocks_served as average_send_time
from
(
select value as gc_current_block_receive_time from v$sysstat
where name = ‘gc current block receive time’
),
(
select value as gc_current_blocks_received from v$sysstat
where name = ‘gc current blocks received’
),
(
select value as gc_current_block_pin_time from v$sysstat
where name = ‘gc current block pin time’
),
(
select value as gc_current_block_flush_time from v$sysstat
where name = ‘gc current block flush time’
),
(
select value as gc_current_block_send_time from v$sysstat
where name = ‘gc current block send time’
),
(
select value as gc_current_blocks_served from v$sysstat
where name = ‘gc current blocks served’
)
);

 

select
namespace ,
dlm_lock_requests,
dlm_pin_requests,
dlm_pin_releases,
dlm_invalidation_requests,
dlm_invalidations
from v$librarycache;

 Comment 

sample coding for referential cursors

on October 10, 2008 at 2:11 pm
Posted In: Oracle odds and ends (Cat)

TEST 2
===========================================================================================
CREATE OR REPLACE PACKAGE PHH AS
  TYPE insttyp IS REF CURSOR RETURN aud$%ROWTYPE;
  aud_rec aud$%ROWTYPE;
  PROCEDURE phh_open_refcursor (aud_cur IN OUT insttyp);
  PROCEDURE phh_close_refcursor (aud_cur IN OUT insttyp);
  PROCEDURE phh_fetch_refcursor (aud_cur IN OUT insttyp, aud_rec IN OUT aud$ROWTYPE);
END PHH;

CREATE OR REPLACE PACKAGE BODY PHH AS
  PROCEDURE phh_open_refcursor (aud_cur IN OUT insttyp) IS
  BEGIN
    IF NOT aud_cur%ISOPEN THEN
       OPEN aud_cur FOR SELECT * FROM aud$ WHERE ROWNUM     END IF;
  END phh_open_refcursor;

  PROCEDURE phh_close_refcursor (aud_cur IN OUT insttyp) IS
  BEGIN
    IF aud_cur%ISOPEN THEN
       CLOSE aud_cur;
    END IF;
  END phh_close_refcursor;

  PROCEDURE phh_fetch_refcursor (aud_cur IN OUT insttyp, aud_rec IN OUT aud$ROWTYPE) IS
  BEGIN
    FETCH aud_cur INTO aud_rec;
  END phh_fetch_refcursor;

  PROCEDURE loop_refcursor IS
    audit_cursor insttyp;
    audit_row aud$rowtype;
  BEGIN
    phh_open_refcursor ( audit_cursor );
    LOOP
      phh_fetch_refcursor ( audit_cursor, audit_row);
      EXIT when audit_cursor%NOTFOUND;
      DBMS_OUTPUT.PUT_LINE(‘SESSION_ID = ‘ || audit_row.sessionid);     
    END LOOP;
    phh_close_refcursor(audit_cursor);
  END loop_refcursor;

END PHH;

begin
  phh.loop_refcursor;
end;

============================================================================================

CREATE OR REPLACE PACKAGE PHH AS
  TYPE insttyp IS REF CURSOR RETURN aud$%ROWTYPE;
  FUNCTION phh_open_refcursor (tst_num number) RETURN insttyp;
END PHH;

CREATE OR REPLACE PACKAGE BODY PHH AS
  FUNCTION phh_open_refcursor (tst_num number) RETURN insttyp IS
  phh_refcursor insttyp;
  BEGIN
  IF NOT phh_refcursor%ISOPEN THEN
     OPEN phh_refcursor FOR SELECT * FROM aud$ WHERE ROWNUM   END IF;
  RETURN phh_refcursor;
  END;
END PHH;

DECLARE
TYPE insttyp IS REF CURSOR /* RETURN aud$%ROWTYPE (SYS_REFCURSOR) */;
auds aud$%ROWTYPE;
tst_cursor insttyp;
tst_num number := 3;
BEGIN

  tst_cursor := phh.phh_open_refcursor(tst_num);
  LOOP
    FETCH tst_cursor INTO auds;
    EXIT WHEN tst_cursor%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(‘SESSION_ID = ‘ || auds.sessionid);
  END LOOP;
  CLOSE tst_cursor;
end;

 

 

 

DECLARE
TYPE empcurtyp IS REF CURSOR RETURN employees%ROWTYPE; — strong
TYPE genericcurtyp IS REF CURSOR; — weak
cursor1 empcurtyp;
cursor2 genericcurtyp;
my_cursor SYS_REFCURSOR; — didn’t need to declare a new type
TYPE deptcurtyp IS REF CURSOR RETURN departments%ROWTYPE;
dept_cv deptcurtyp; — declare cursor variable

DECLARE
TYPE TmpCurTyp IS REF CURSOR RETURN employees%ROWTYPE;
tmp_cv TmpCurTyp; — declare cursor variable
TYPE EmpCurTyp IS REF CURSOR RETURN tmp_cv%ROWTYPE;
emp_cv EmpCurTyp; — declare cursor variable

DECLARE
dept_rec departments%ROWTYPE; — declare record variable
TYPE DeptCurTyp IS REF CURSOR RETURN dept_rec%TYPE;
dept_cv DeptCurTyp; — declare cursor variable

DECLARE
TYPE EmpRecTyp IS RECORD (
  employee_id NUMBER,
  last_name VARCHAR2(25),
  salary NUMBER(8,2));

TYPE EmpCurTyp IS REF CURSOR RETURN EmpRecTyp;
emp_cv EmpCurTyp; — declare cursor variable

DECLARE
TYPE empcurtyp IS REF CURSOR RETURN employees%ROWTYPE;
emp empcurtyp;
— after result set is built, process all the rows inside a single procedure
— rather than calling a procedure for each row

PROCEDURE process_emp_cv (emp_cv IN empcurtyp) IS
  person employees%ROWTYPE;
BEGIN
  DBMS_OUTPUT.PUT_LINE(‘—–‘);
  DBMS_OUTPUT.PUT_LINE(‘Here are the names from the result set:’);
  LOOP
    FETCH emp_cv INTO person;
    EXIT WHEN emp_cv%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(‘Name = ‘ || person.first_name || ‘ ‘ || person.last_name);
  END LOOP;
END;

BEGIN
— First find 10 arbitrary employees.
  OPEN emp FOR SELECT * FROM employees WHERE ROWNUM   process_emp_cv(emp);
  CLOSE emp;
— find employees matching a condition.
  OPEN emp FOR SELECT * FROM employees WHERE last_name LIKE ‘R%’;
  process_emp_cv(emp);
  CLOSE emp;
END;
/

 

 Comment 

cleaning and using flash recovery area (Oracle 11g)

on October 10, 2008 at 1:59 pm
Posted In: Oracle Flashback Notes (Cat)

FLASH RECOVERY AREA options

DB_RECOVERY_FILE_DEST_SIZE;
DB_RECOVERY_FILE_DEST;

SELECT * FROM V$RECOVERY_FILE_DEST;
SELECT * FROM V$FLASH_RECOVERY_AREA_USAGE;
SQL> alter system set DB_RECOVERY_FILE_DEST_SIZE= ;
RMAN> backup device type ‘sbt_tape’ recovery area;
RMAN> configure retention policy to recovery window of 5 days;
RMAN> cONFIGURE ARCHIVELOG DELETION POLICY TO BACKED UP 1 TIMES TO SBT;
RMAN> DELETE EXPIRED ARCHIVELOG ALL;
RMAN> DELETE OBSOLETE ARCHIVELOG ALL;

SELECT object_type, message_type, message_level, reason, suggested_action FROM dba_outstanding_alerts;

backup recovery area;

RMAN> delete expired archivelog all;

=================
SELECT * FROM V$RECOVERY_FILE_DEST;
NAME——————————————————————
SPACE_LIMIT
SPACE_USED  SPACE_RECLAIMABLE NUMBER_OF_FILES
———– ———- —————– —————
/opt/oracle/product/1010/dbs/ora_flash_area
1073741824  633155072         0               8

RMAN> DELETE BACKUPSET 45;
using channel ORA_DISK_1
using channel ORA_SBT_TAPE_1
List of Backup Pieces
BP Key  BS Key  Pc# Cp# Status      Device Type Piece Name
——- ———- — ———– ———– ———-
52      45      1   1   AVAILABLE   DISK        opt/oracle/product/1010/dbs/ora_flash_area/DB10G/backupset/2005_06_15/o1_mf_ncsnf_TAG20050615T215053_1c0odcbg_.bkp
Do you really want to delete the above objects (enter YES or NO)? yes
deleted backup piece
backup piece handle=/opt/oracle/product/1010/dbs/ora_flash_area/DB10G/backupset/2005_06_15/o1_mf_ncsnf_TAG20050615T215053_1c0odcbg_.bkp
recid=52 stamp=561073891
Deleted 1 objects
SQL>
==================

Disk Quota =
Size of a copy of database +
Size of an incremental backup +
Size of (n+1) days of archived redo logs +
Size of (y+1) days of foreign archived redo logs (for logical standby) +
Size of control file +
Size of an online redo log member * number of log groups +
Size of flashback logs (based on DB_FLASHBACK_RETENTION_TARGET value)

 

 Comment 

dr scenarios dataguard

on October 10, 2008 at 1:58 pm
Posted In: Oracle Data Guard Notes (Cat)

LIVE DATABASES
==============

alter system switch logfile;
alter system switch logfile;
Shutdown all but 1 instance on all databases.
SELECT switchover_status FROM v$database;
ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY WITH SESSION SHUTDOWN;
srvctl stop database -d
srvctl start instance -d -i -o mount
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=DEFER;
SELECT open_mode, database_role FROM    v$database;

STANDBY DATABASES
=================

RECOVER MANAGED STANDBY DATABASE NODELAY DISCONNECT;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY WITH SESSION SHUTDOWN;
srvctl stop database -d
srvctl start instance -d -i -o open
SELECT open_mode, database_role FROM    v$database;
ON OLD LIVE – ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT;
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=ENABLE;
ALTER SYSTEM SWITCH LOGFILE;
Restart the rest of the standby instances.

Ensure the services start up; if not then: dba/scripts/services

 Comment 

create a logical host using an application vip

on October 10, 2008 at 1:57 pm
Posted In: Oracle odds and ends (Cat)

Oracle’s Application VIP is used to create the Logical Host.

 

Steps

  1. Sign onto the database server as Oracle.
     
  2. Create the Logical Host profile resource.
    ${ORA_CRS_HOME}/bin/crs_profile -create ${MYVIP} \
    -t application \
    -a ${ORA_CRS_HOME}/bin/usrvip \
    -o oi=eth1,ov=${IP_ADDRESS},on=255.255.255.0

    where MYVIP = made up from –vip
    and IP_ADDRESS = as defined in /etc/hosts.

    will be either “hostaa”, “hostab“, “hostbc” or “hostbd” depending on whether the server is in the “a” or “b“ environment.  i.e. for database aa on hostaa the Logical Host Name is “enva-hosta-vip“.
     

  3. Register the profile resource with CRS.
    ${ORA_CRS_HOME}/bin/crs_register ${MYVIP}
     
  4. As ROOT change the Ownership.
    ${ORA_CRS_HOME}/bin/crs_setperm ${MYVIP} -o root
     
  5. As ROOT set the permissions to Read and Execute for Oracle.
    ${ORA_CRS_HOME}/bin/crs_setperm ${MYVIP} -u user:oracle:r-x
     
  6. Start the profile resource.
    ${ORA_CRS_HOME}/bin/crs_start ${MYVIP}
     
  7. Check the profile resource is ONLINE and note the Server its running on.
    crsstat | grep ${MYVIP}
     
  8. Check the Host Interface Configuration on the Server noted above.
    ifconfig –a

 

 Comment 

connect strings for sqlnet

on October 10, 2008 at 1:56 pm
Posted In: Oracle odds and ends (Cat)

INSTANCE_NAME = HOSTA
SERVICE_NAME=SVCA

SID=SIDA

CONNECT system@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=1.2.3.4)(PORT=1521))
(connect_data=(sid=hosta
)))

 

CONNECT system@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=1.2.3.4)(PORT=1521))
(connect_data=(service_name=svca
)))

CONNECT system@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=1.2.3.4)(PORT=1521))
(connect_data=(sid=sida
)))

CONNECT system@(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=1.2.3.4)(PORT=1521))
(connect_data=(sid=sida)(service_name=svca
)))

 Comment 

notes on how to cluster oms 10g grid control

on October 10, 2008 at 1:55 pm
Posted In: Oracle RAC (Cat)

OMS AND AGENTS
==============
http://www.oracle.com/technology/deploy/availability/pdf/MAA_WP_10gR2_EnterpriseManagerBestPractices.pdf

Install at least one additional OMS using the OUI option ‘Add Additional Management Service’.

$ORACLE_HOME/sysman/config/emoms.properities
oracle.sysman.eml.mntr.emdRepConnectDescriptor=
   (DESCRIPTION=(ADDRESS_LIST=(FAILOVER=ON)
     (ADDRESS=(PROTOCOL=TCP)(HOST=hostname.oms1.com) (PORT=1521))
     (ADDRESS=(PROTOCOL=TCP)(HOST=hostname.oms2.com) (PORT=1521))
   (CONNECT_DATA=(SERVICE_NAME=EMREP)))

execute: emctl config oms loader -shared yes -dir ’

REPOSITORY DB
=============
• Enable ARCHIVELOG Mode
• Enable Block Checksums
• Configure the Size of Redo Log Files and Groups Appropriately
• Use a Flash Recovery Area
• Enable Flashback Database
• Use Fast-Start Fault Recovery to Control Instance Recovery Time
• Enable Database Block Checking
• Set DISK_ASYNCH_IO
(Oracle® Database High Availability Best Practices 10g Release 2 (10.2))

AGENTS
======
Use hardware Server Load Balancer (SLB) between the agents and the OMSes.
Modify the ServerName property defined in the Oracle HTTP Server configuration file at
$ORACLE_HOME/Apache/Apache/conf/ssl.conf
to point to the Virtual host name being managed by the Load Balancer.

Modify the ‘Port’ in the Oracle HTTP Server configuration file at
$ORACLE_HOME/Apache/Apache/conf/ssl.conf to be ‘443.

Note:: complete outline of the steps required to configure a hardware Load Balancer for EM High Availability
is published on Web IV, Note 353074.1, How to configure Grid Control 10.2 Management Servers behind a Server Load Balancer (SLB)
(https://metalink2.oracle.com/metalink/plsql/f?p=130:14:3505972173805869015::::p14_database_id,p14_docid,p14_show_header,p14_show_help,p14_black_frame,p14_font:NOT,353074.1,1,0,1,helvetica)

DR
==
• Create standby database
• Return to the Enterprise Manager console and discover the new standby database.
• Navigate to primary database targets page and follow the instructions (below) to bring the primary and standby database under Data Guard Broker Control.
• If the standby database instance is to be a RAC cluster, follow the steps documented in the white paper ‘MAA / Data Guard 10g Release 2 Setup Guide –Creating a RAC Logical Standby for a RAC Primary’
Configure the primary repository and standby repository with the recommendations listed in Section 2.4 of the Oracle® Database High Availability Best Practices 10g Release 2 (10.2) Part Number B25159-01.

Use the ‘Create Additional Management Service’ option of the EM Installer to add the secondary OMS processes.
1. Configure the OMS to point to the repository running on the primary during install.
2. After the install is complete, shutdown the OMS and edit the $ORACLE_HOME/sysman/config/emoms.properities file to
modify the following properties to point the OMS to the standby database:
  oracle.sysman.eml.mntr.emdRepConnectDescriptor=
  oracle.sysman.emSDK.svlt.ConsoleServerName=
add the following property:
  em.FastConnectionFailover=true

Configure Triggers to start OMS at standby site:
An ability of the database is the facility to execute Oracle triggers to be fired database startup.
Combined with Data Guard these triggers can be configured to start OMS processes at the standby site after a Data Guard switchover or failover occurs. Examples of these triggers as they relate to Enterprise Manager are in the Appendix.

A complete reference on the underlying technology used to automate these client failovers is documented in the Client Failover Best Practices for Highly Available Oracle Databases: Oracle Database 10g Release 2, located on the OTN on the Maximum Availability Architecture Page.

Note: The standby OMS processes can be kept ready for service (not started) until the Data Guard failover triggers are initiated or be configured to service requests from the primary if network latency between the primary and standby is low.

Examples of DB Disaster Recovery Triggers & Scripts:
====================================================
The following trigger will be fired on the start up of any instance of a database.
The trigger will call the script ‘start_oms’, which will start an OMS process.
This facility can be used to start the OMS for a standby database in the event of an unplanned site outage

CREATE OR REPLACE TRIGGER manage_service after startup on database
DECLARE
  role VARCHAR(30);
BEGIN
  SELECT DATABASE_ROLE INTO role FROM V$DATABASE;
  IF role = ‘PRIMARY’ THEN
    DBMS_SERVICE.START_SERVICE(‘gcha_oms’);
    begin
      dbms_scheduler.create_job(
        job_name=>’oms_start’,
        job_type=>’executable’,
        job_action=>’

 Comment 

Remedy notes on bst and utc date formats in oracle

on October 10, 2008 at 1:54 pm
Posted In: Oracle odds and ends (Cat)

create or replace
FUNCTION fn_adjusted_date (input_date NUMBER)  
RETURN DATE       IS  
loutput_date   DATE;  
linput_date      DATE;  
lyear               INT;  
lcurrentyear     INT;  
loffset             NUMBER(20,16) :=0;
BEGIN    

  linput_date := TO_DATE (’01-JAN-1970′) + input_date * 0.0000115740740740741;  

  IF input_date IS NULL     
  THEN
    loutput_date:= NULL;   
  ELSE     
    SELECT linput_date + DECODE (SUBSTR (TZ_OFFSET (DBTIMEZONE), 1, 1), ‘-‘, -1, ‘+’, 1) * TO_DSINTERVAL
   (‘0 ‘ || SUBSTR (TZ_OFFSET (DBTIMEZONE), 2, 5)|| ‘:00’) INTO loutput_date FROM DUAL;       
  END IF;  

RETURN loutput_date;

EXCEPTION   
  WHEN NO_DATA_FOUND  
    THEN NULL;

END fn_adjusted_date;

As per the Remedy 7.1 Database Reference guide,

Appendix A

To convert the date and time format for an Oracle® database

1 Using any front-end tool that enables direct access to an Oracle SQL database,
log in as a user with write access to the AR System tables.

2 Type the following command:
SELECT TO_CHAR(TO_DATE(’01/01/1970 00:00:00′, ‘MM/DD/YYYYHH24:MI:SS’) + 
            ((C + )/(60*60*24)),’MM/DD/YYYY HH24:MI:SS’) FROM T;
where      
  is the number of the column for the date and time field,
  is the number of the form table, 
  is a positive or negative number representing the number of seconds later or earlier than GMT.

See the your Oracle documentation for information about the TO_DATE and TO_CHARfunctions.

select to_char(sysdate,’dd-mon-yy hh24:mi:ss’),
       to_char(sysdate+to_dsinterval(‘0 ‘ || SUBSTR (TZ_OFFSET (DBTIMEZONE), 2, 5)|| ‘:00′),’dd-mon-yy hh24:mi:ss’)
from dual;

declare loutput_date date;
  linput_date date;
  tmp varchar2(30);
begin
  linput_date := sysdate;
  SELECT linput_date + DECODE (SUBSTR (TZ_OFFSET (DBTIMEZONE), 1, 1), ‘-‘, -1, ‘+’, 1) * TO_DSINTERVAL
   (‘0 ‘ || SUBSTR (TZ_OFFSET (DBTIMEZONE), 2, 5)|| ‘:00’) INTO loutput_date FROM DUAL;
  select to_char(loutput_date,’dd-mon-yy hh24:mi:ss’) into tmp from dual;
  dbms_output.put_line(tmp);
end;
/

select DBTIMEZONE from dual;
ALTER database SET TIME_ZONE = ‘America/Denver’;
ALTER database SET TIME_ZONE = ‘-07:00’;
select SYSTIMESTAMP from dual;
select tzname,tzabbrev from V$TIMEZONE_NAMES where tzabbrev = ‘GMT’

select to_char(current_date,’dd-mon-yy hh24:mi:ss’) from dual;

You need to stop using DATE and start using TIMESTAMP WITH TIMEZONE datatypes.

Both systems will store the same date-time value, but they will have different timezone settings.

When you look at the value of the TIMESTAMP WITH TIMEZONE, it includes both the date-time and the timezone offset.

This means that even on a single machine you can have databases with different timezones.

 Comment 

Failover and Switchover with Flashback (Oracle 11g)

on August 27, 2008 at 3:24 pm
Posted In: Oracle Flashback Notes (Cat)

On the primary database defer log shipping

ALTER SYSTEM ARCHIVE LOG CURRENT;
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=DEFER;
SELECT TO_CHAR(CURRENT_SCN) FROM V$DATABASE;

# on the standby enable flashback and disable recovery
ALTER SYSTEM SET DB_RECOVERY_FILE_DEST_SIZE=20G;
ALTER SYSTEM SET DB_RECOVERY_FILE_DEST=’/oraarch1′;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
create restore point before_start guarantee flashback database;
ALTER DATABASE ACTIVATE STANDBY DATABASE;
ALTER DATABASE OPEN;

# Run read/write test on opened standby database.

# flashback and switch back to physical standby
STARTUP MOUNT FORCE;
flashback database to restore point before_start;
drop restore point before_start;
ALTER DATABASE CONVERT TO PHYSICAL STANDBY;
STARTUP MOUNT FORCE;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT;

# on the primary database enable log shipping
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=ENABLE;

 Comment 

Failover and Switchover with Flashback from Dave Moyes

on August 27, 2008 at 3:24 pm
Posted In: Oracle Data Guard Notes (Cat)

On the primary database defer log shipping

ALTER SYSTEM ARCHIVE LOG CURRENT;
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=DEFER;
SELECT TO_CHAR(CURRENT_SCN) FROM V$DATABASE;

# on the standby enable flashback and disable recovery
ALTER SYSTEM SET DB_RECOVERY_FILE_DEST_SIZE=20G;
ALTER SYSTEM SET DB_RECOVERY_FILE_DEST=’/oraarch1′;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;
create restore point before_start guarantee flashback database;
ALTER DATABASE ACTIVATE STANDBY DATABASE;
ALTER DATABASE OPEN;

# Run read/write test on opened standby database.

# flashback and switch back to physical standby
STARTUP MOUNT FORCE;
flashback database to restore point before_start;
drop restore point before_start;
ALTER DATABASE CONVERT TO PHYSICAL STANDBY;
STARTUP MOUNT FORCE;
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT;

# on the primary database enable log shipping
ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=ENABLE;

 Comment 

Creating a Standby Database That Uses OMF or ASM

on August 27, 2008 at 3:16 pm
Posted In: Oracle Data Guard Notes (Cat)

Perform the following tasks to prepare for standby database creation:

  1. Enable forced logging on the primary database.
  2. Enable archiving on the primary database.
  3. Set all necessary initialization parameters on the primary database.
  4. Create an initialization parameter file for the standby database.
  5. If the primary database is configured to use OMF, then Oracle recommends that the standby database be configured to use OMF, too. To do this, set the DB_CREATE_FILE_DEST and DB_CREATE_ONLINE_LOG_DEST_n initialization parameters to appropriate values. Maintenance and future role transitions are simplified if the same disk group names are used for both the primary and standby databases.
  6. Set the STANDBY_FILE_MANAGEMENT initialization parameter to AUTO.
  7. Configure Oracle Net, as required, to allow connections to the standby database.
  8. Create a remote login password file for the standby database. Use the same password for the SYS account as on the primary database.
  9. Start the standby database instance without mounting the control file.

Perform the following tasks to create the standby database:

  1. If the standby database is going to use ASM, create an ASM instance if one does not already exist on the standby database system.
  2. Use the RMAN BACKUP command to create a backup set that contains a copy of the primary database’s datafiles, archived log files, and a standby control file.
  3. Use the RMAN DUPLICATE … FOR STANDBY command to copy the datafiles, archived redo log files and standby control file in the backup set to the standby database’s storage area.

The DUPLICATE … FOR STANDBY command performs the actual data movement at the standby instance. If the backup set is on tape, the media manager must be configured so that the standby instance can read the backup set. If the backup set is on disk, the backup pieces must be readable by the standby instance, either by making their primary path names available through NFS, or by copying them to the standby system and using RMAN CATALOG BACKUPPIECE command to catalog the backup pieces before restoring them.

After you successfully complete these steps, continue with the steps in Section 3.2.7, to verify the configuration of the physical standby database.

To create a logical standby database, continue with the standby database creation process described in Chapter 4, but with the following modifications:

  1. For a logical standby database, setting the DB_CREATE_FILE_DEST parameter does not force the creation of OMF filenames. However, if this parameter was set on the primary database, it must also be set on the standby database.
  2. After creating a logical standby control file on the primary system, do not use an operating system command to copy this file to the standby system. Instead, use the RMAN RESTORE CONTROLFILE command to restore a copy of the logical standby control file to the standby system.
  3. If the primary database uses OMF files, use RMAN to update the standby database control file to use the new OMF files created on the standby database. To perform this operation, connect only to the standby database, as shown in the following example:
> RMAN TARGET sys/oracle@lstdby RMAN> CATALOG START WITH '+stby_diskgroup'; RMAN> SWITCH DATABASE TO COPY; 

After you successfully complete these steps, continue with the steps in Section 4.2.5 to start, recover, and verify the logical standby database.

 Comment 

STANDBY ARCHIVE GAPS

on August 27, 2008 at 3:14 pm
Posted In: Oracle Data Guard Notes (Cat)

V$ARCHIVED_LOG

V$ARCHIVE_DEST_STATUS

V$LOG

To determine if there is an archive gap, query the V$ARCHIVED_LOG and V$LOG views. If an archive gap exists, the output of the query specifies the thread number and log sequence number of all log files in the archive gap. If there is no archive gap for a given thread, the query returns no rows.

Identify the log files in the archive gap

Query the V$ARCHIVED_LOG and V$LOG views on the standby database. For example, the following query shows there is a difference in the RECD and SENT sequence numbers for the destination specified by DEST_ID=2, indicating that there is a gap:

SQL> SELECT MAX(R.SEQUENCE#) LAST_SEQ_RECD, MAX(L.SEQUENCE#) LAST_SEQ_SENT FROM   
2> V$ARCHIVED_LOG R, V$LOG L WHERE   
3> R.DEST_ID=2 AND L.ARCHIVED='YES';  
LAST_SEQ_RECD LAST_SEQ_SENT ------------- -------------             7            10 

Use the following query to determine the names of the archived redo log files on the local system that must be copied to the standby system that has the gap:

SQL> SELECT NAME FROM V$ARCHIVED_LOG WHERE THREAD#=1 AND DEST_ID=1 AND   
2> SEQUENCE# BETWEEN 7 AND 10; 
 NAME -------------------------------------------------------------------------------- 
/primary/thread1_dest/arcr_1_7.arc 
/primary/thread1_dest/arcr_1_8.arc 
/primary/thread1_dest/arcr_1_9.arc 
/primary/thread1_dest/arcr_1_10.arc

12.11.3 Manually Transmitting Log Files in the Archive Gap to the Standby Site

After you have obtained the sequence numbers of the log files in the archive gap, you can obtain their filenames by querying the V$ARCHIVED_LOG view on the primary site. The archived redo log path names on the standby site are generated by the STANDBY_ARCHIVE_DEST and LOG_ARCHIVE_FORMAT parameters in the standby initialization parameter file.

If the standby database is on the same site as the primary database, or the standby database is on a remote site with a different directory structure than the primary database, the path names for the log files on the standby site cannot be the same as the path names of the log files archived by the primary database. Before transmitting the redo data to the standby site, determine the correct path names for the archived redo log files at the standby site.

To copy log files in an archive gap to the standby site

  1. Review the list of archive gap log files that you obtained earlier. For example, assume you have the following archive gap:
  2. THREAD#    LOW_SEQUENCE#   HIGH_SEQUENCE# ---------- -------------   --------------        1             460              463        2             202              204        3             100              100 

    If a thread appears in the view, then it contains an archive gap. You need to copy log files from threads 1, 2, and 3.

  3. Determine the path names of the log files in the archive gap that were transmitted by the primary database. After connecting to the primary database, issue a SQL query to obtain the name of a log file in each thread. For example, use the following SQL statement to obtain filenames of log files for thread 1:
  4. SQL> SELECT NAME FROM V$ARCHIVED_LOG WHERE THREAD#=1 AND DEST_ID=1   
    2> AND SEQUENCE# > 459 AND SEQUENCE# < 464;  
    NAME --------------------------------------------------------------------- 
    /primary/thread1_dest/arcr_1_460.arc 
    /primary/thread1_dest/arcr_1_461.arc 
    /primary/thread1_dest/arcr_1_462.arc 
    /primary/thread1_dest/arcr_1_463.arc 
    4 rows selected 

    Perform similar queries for threads 2 and 3.

  5. On the standby site, review the settings for STANDBY_ARCHIVE_DEST and LOG_ARCHIVE_FORMAT in the standby initialization parameter file. For example, you discover the following:
  6. STANDBY_ARCHIVE_DEST = /standby/arc_dest/ LOG_ARCHIVE_FORMAT = log_%t_%s_%r.arc 

    These parameter settings determine the filenames of the archived redo log files at the standby site.

  7. On the primary site, copy the log files in the archive gap from the primary site to the standby site, renaming them according to values for STANDBY_ARCHIVE_DEST and LOG_ARCHIVE_FORMAT. For example, enter the following copy commands to copy the archive gap log files required by thread 1:
  8. % cp /primary/thread1_dest/arcr_1_460.arc /standby/arc_dest/log_1_460.arc 
    % cp /primary/thread1_dest/arcr_1_461.arc /standby/arc_dest/log_1_461.arc 
    % cp /primary/thread1_dest/arcr_1_462.arc /standby/arc_dest/log_1_462.arc 
    % cp /primary/thread1_dest/arcr_1_463.arc /standby/arc_dest/log_1_463.arc 

    Perform similar commands to copy archive gap log files for threads 2 and 3.

  9. On the standby site, if the LOG_ARCHIVE_DEST and STANDBY_ARCHIVE_DEST parameter values are not the same, then copy the archive gap log files from the STANDBY_ARCHIVE_DEST directory to the LOG_ARCHIVE_DEST directory. If these parameter values are the same, then you do not need to perform this step.

For example, assume the following standby initialization parameter settings:

STANDBY_ARCHIVE_DEST = /standby/arc_dest/ LOG_ARCHIVE_DEST = /log_dest/ 

Because the parameter values are different, copy the archived redo log files to the LOG_ARCHIVE_DEST location:

% cp /standby/arc_dest/* /log_dest/ 

When you initiate manual recovery, the Oracle database looks at the LOG_ARCHIVE_DEST value to determine the location of the log files.

Now that all required log files are in the STANDBY_ARCHIVE_DEST directory, you can proceed to Section 12.11.4 to apply the archive gap log files to the standby database. See also Section 8.5.4.4 and the V$ARCHIVED_LOG view in Chapter 16.

12.11.4 Manually Applying Log Files in the Archive Gap to the Standby Database

After you have copied the log files in the archive gap to the standby site, you can apply them using the RECOVER AUTOMATIC statement.

To apply the archived redo log files in the archive gap

  1. Start up and mount the standby database (if it is not already mounted). For example, enter:
  2. SQL> STARTUP MOUNT PFILE=/oracle/admin/pfile/initSTBY.ora 
  3. Recover the database using the AUTOMATIC option:
  4. SQL> ALTER DATABASE RECOVER AUTOMATIC STANDBY DATABASE; 

    The AUTOMATIC option automatically generates the name of the next archived redo log file needed to continue the recovery operation.

    After recovering the available log files, the Oracle database prompts for the name of a log file that does not exist. For example, you might see:

    ORA-00308: cannot open archived log '/oracle/standby/standby_logs/arcr_1_540.arc' 
    ORA-27037: unable to obtain file status SVR4 Error: 
    2: No such file or directory Additional information: 
    3 Specify log: {=suggested | filename | AUTO | CANCEL} 
  5. Cancel recovery after the Oracle database applies the available log files by typing CTRL/C:
  6. SQL>  Media recovery cancelled. 

    The following error messages are acceptable after recovery cancellation and do not indicate a problem:

    ORA-01547: warning: RECOVER succeeded but OPEN RESETLOGS would get error below 
    ORA-01194: file 1 needs more recovery to be consistent 
    ORA-01110: data file 1: 'some_filename' 
    ORA-01112: media recovery not started 
  7. After you finish manually applying the missing log file, you can restart log apply services on the standby database, as follows:
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;
 Comment 

Using RMAN Incremental Backups to Roll Forward a Physical Standby Database

on August 27, 2008 at 3:11 pm
Posted In: Oracle Rman Notes (Cat)

Physical Standby Database Lags Far Behind the Primary Database

Physical Standby Database Lags Far Behind the Primary Database

Follow this step-by-step procedure to roll forward a physical standby database that has fallen far behind the primary database.

Note: The steps in this section can also be used to resolve problems if a physical standby database has lost or corrupted archived redo data or has an unresolveable archive gap.

  1. On the standby database, query the V$DATABASE view and record the current SCN of the standby database:
  2. SQL> SELECT CURRENT_SCN FROM V$DATABASE; CURRENT_SCN -----------      233995 
  3. Stop Redo Apply on the standby database:
  4. SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL; 
  5. Connect to the primary database as the RMAN target and create an incremental backup from the current SCN of the standby database that was recorded in step 1:
  6. RMAN> BACKUP INCREMENTAL FROM SCN 233995 DATABASE FORMAT '/tmp/ForStandby_%U' tag 'FOR STANDBY'; 

    Note:

    RMAN does not consider the incremental backup as part of a backup strategy at the source database. Hence:

    The backup is not suitable for use in a normal RECOVER DATABASE operation at the source database

    The backup is not cataloged at the source database

    The backup sets produced by this command are written to the /dbs location by default, even if the flash recovery area or some other backup destination is defined as the default for disk backups.

    You must create this incremental backup on disk for it to be useful. When you move the incremental backup to the standby database, you must catalog it at the standby as described in Oracle Database Backup and Recovery Advanced User’s Guide. Backups on tape cannot be cataloged.

  7. Transfer all backup sets created on the primary system to the standby system (note that there may be more than one backup file created):
  8. SCP /tmp/ForStandby_* standby:/tmp 
  9. Connect to the standby database as the RMAN target, and catalog all incremental backup pieces:
  10. RMAN> CATALOG START WITH '/tmp/ForStandby_'; 
  11. Connect to the standby database as the RMAN target and apply incremental backups
  12. RMAN> RECOVER DATABASE NOREDO; 
  13. Remove the incremental backups from the standby system:
  14. RMAN> DELETE BACKUP TAG 'FOR STANDBY'; 
  15. Manually remove the incremental backups from the primary system:
  16. rm /tmp/ForStandby_* 
  17. Start Redo Apply on the physical standby database:
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT;
 Comment 

Using RMAN Incremental Backups to Roll Forward a Physical Standby Database

on August 27, 2008 at 3:11 pm
Posted In: Oracle Rman Notes (Cat)

Physical Standby Database Lags Far Behind the Primary Database

Physical Standby Database Lags Far Behind the Primary Database

Follow this step-by-step procedure to roll forward a physical standby database that has fallen far behind the primary database.

Note: The steps in this section can also be used to resolve problems if a physical standby database has lost or corrupted archived redo data or has an unresolveable archive gap.

  1. On the standby database, query the V$DATABASE view and record the current SCN of the standby database:
  2. SQL> SELECT CURRENT_SCN FROM V$DATABASE; CURRENT_SCN -----------      233995 
  3. Stop Redo Apply on the standby database:
  4. SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL; 
  5. Connect to the primary database as the RMAN target and create an incremental backup from the current SCN of the standby database that was recorded in step 1:
  6. RMAN> BACKUP INCREMENTAL FROM SCN 233995 DATABASE FORMAT '/tmp/ForStandby_%U' tag 'FOR STANDBY'; 

    Note:

    RMAN does not consider the incremental backup as part of a backup strategy at the source database. Hence:

    The backup is not suitable for use in a normal RECOVER DATABASE operation at the source database

    The backup is not cataloged at the source database

    The backup sets produced by this command are written to the /dbs location by default, even if the flash recovery area or some other backup destination is defined as the default for disk backups.

    You must create this incremental backup on disk for it to be useful. When you move the incremental backup to the standby database, you must catalog it at the standby as described in Oracle Database Backup and Recovery Advanced User’s Guide. Backups on tape cannot be cataloged.

  7. Transfer all backup sets created on the primary system to the standby system (note that there may be more than one backup file created):
  8. SCP /tmp/ForStandby_* standby:/tmp 
  9. Connect to the standby database as the RMAN target, and catalog all incremental backup pieces:
  10. RMAN> CATALOG START WITH '/tmp/ForStandby_'; 
  11. Connect to the standby database as the RMAN target and apply incremental backups
  12. RMAN> RECOVER DATABASE NOREDO; 
  13. Remove the incremental backups from the standby system:
  14. RMAN> DELETE BACKUP TAG 'FOR STANDBY'; 
  15. Manually remove the incremental backups from the primary system:
  16. rm /tmp/ForStandby_* 
  17. Start Redo Apply on the physical standby database:
SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE DISCONNECT;
 Comment 

Using a Physical Standby Database for Read/Write Testing and Reporting

on August 27, 2008 at 3:09 pm
Posted In: Oracle Data Guard Notes (Cat)

Using a combination of Data Guard, restore points, and Flashback Database, a physical standby database can be opened temporarily in read/write mode for development, reporting, or testing purposes, and then flashed back to a point in the past to be reverted back to a physical standby database. When the database is flashed back, Data Guard automatically synchronizes the standby database with the primary database, without the need to re-create the physical standby database from a backup copy of the primary database.

Figure 12-7 shows a physical standby database being activated as a read/write clone database, resynchronized with the primary database, and eventually flashed back and reverted to its physical standby database role. You can repeat this cycle of activate, flashback and revert as many times as is necessary.

Figure 12-7 Using a Physical Standby Database As a Testing and Reporting Database

Description of “Figure 12-7 Using a Physical Standby Database As a Testing and Reporting Database”
Caution:

While the database is activated, it is not receiving redo data from the primary database and cannot provide disaster protection. It is recommended that there be at least two physical standby databases participating in the configuration so that the primary database remains protected against data loss.

Perform the following steps to activate the physical standby database as a production database and later resynchronize it with the primary database.

Step 1 Prepare the physical standby database to be activated.

  1. Set up a flash recovery area.
  2. On the physical standby database that will be activated for read/write access, you should set the following initialization parameters to ensure a guaranteed restore point can be created. This scenario sets up the flash recovery area in the /arch/oradata location:

    SQL> ALTER SYSTEM SET DB_RECOVERY_FILE_DEST_SIZE=20G; SQL> ALTER SYSTEM SET DB_RECOVERY_FILE_DEST='/arch/oradata'; 
  3. Cancel Redo Apply and create a guaranteed restore point.

On the physical standby database, stop Redo Apply and create a restore point:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL; SQL> CREATE RESTORE POINT before_application_patch GUARANTEE FLASHBACK DATABASE; 

When you create a guaranteed restore point, you associate an easy-to-remember name with a timestamp or SCN so that you can later flash back the database to a name instead of specifying an exact SCN or time.

Step 2 Prepare the primary database to have the physical standby be diverged.

  1. Archive the current log file.
  2. On the primary database, switch logs so the SCN of the restore point (created in step 1) will be archived on the physical standby database:

    SQL> ALTER SYSTEM ARCHIVE LOG CURRENT; 

    When using standby redo log files, this step is essential to ensure the database can be properly flashed back to the restore point.

  3. Defer log archive destinations pointing to the standby that will be activated.

On the primary database (on all instances if this is a Real Applications Cluster), defer the archival of redo data to the destination associated with the physical standby database that will be opened. For example:

SQL> ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=DEFER;

Step 3 Activate the physical standby database.

On the physical standby database, perform the following steps:

  1. Activate the physical standby database:
  2. SQL> ALTER DATABASE ACTIVATE STANDBY DATABASE; 
  3. If the physical standby database has been opened read-only since the instance was started, perform this step. Otherwise, skip to step 3.
  4. Enter the following statement to shut down and restart the physical standby database:

    SQL> STARTUP MOUNT FORCE; 
  5. Set the protection mode to maximum performance and open the database for read/write access:
SQL> ALTER DATABASE SET STANDBY DATABASE TO MAXIMIZE PERFORMANCE; SQL> ALTER DATABASE OPEN; 

After the standby database is activated, its protection mode is downgraded to the maximum performance mode, because there is no standby database configured to protect the database against data loss while it is temporarily activated as a production database. Note that this protection mode setting does not affect the protection mode of the original primary database, it affects only the activated standby database.

When the activated standby database is converted back to a physical standby database, its protection mode is automatically changed to match that of the original primary database.

If the standby database that was opened read/write temporarily has remote archive log destinations, you might need to disable them. In this way, the read/write testing or reporting database will not propagate its temporary changes to other standby databases in the original Data Guard environment.

Step 4 Use the activated database for reporting or testing.

Once the standby database has been activated, you can run reporting tools or perform other testing and activities for days or even weeks, independent of the primary database.

Caution:

While the database is activated, it is not receiving redo data from the primary database and cannot provide disaster protection. It is recommended that there be at least two physical standby databases participating in the configuration so that the primary database remains protected against data loss.

Also, any results stored in the activated database will be lost when you later flash back the database. Results that should be saved must be copied out of the activated database before flashing it back.

Step 5 Revert the activated database back to a physical standby database.

After you finish testing, you need to resynchronize the activated database with the primary database. Issue the following statements on the activated database to quickly flash it back to the guaranteed restore point and resynchronize it with the primary database:

SQL> STARTUP MOUNT FORCE; SQL> FLASHBACK DATABASE TO RESTORE POINT before_application_patch; SQL> ALTER DATABASE CONVERT TO PHYSICAL STANDBY; SQL> STARTUP MOUNT FORCE;

Step 6 Catch up the standby database to the primary database.

The method you use will depend on how far the activated standby database lags behind the primary database in its application of redo data:

Let archive gap resolution fetch all missing archived redo log files and allow Redo Apply to apply the gap.

If the activated database has not fallen too far behind the original primary database, issue the following statement on the standby database to resynchronize it with the primary database and restart Redo Apply. For example:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT; 

Then, go to Step 7.

Create an incremental backup on the primary and apply it to the standby.

If the activated database has fallen too far behind the original primary database (for example, if there are not sufficient log files available), you can take an incremental backup from the primary database and apply it to the standby database. See Section 12.7.1 for information about using RMAN incremental backups to resynchronize the standby database with the primary database.

Note:

If the standby database lags very far behind the primary database, it may be quicker to apply an incremental backup created from the primary database using the steps in Section 12.7.1.

After you apply an incremental backup to the standby database, you typically need to apply more redo to the standby database to activate the physical standby database again for read/write testing or reporting purposes. More specifically, you might need to apply the redo generated by the primary database while the incremental backup was taken. Otherwise, issuing an ALTER DATABSE ACTIVATE STANDBY DATABASE will return an error.

Step 7 Reenable archiving to the physical standby database destination.

On the primary database, issue the following statement to reenable archiving to the physical standby database:

SQL> ALTER SYSTEM SET LOG_ARCHIVE_DEST_STATE_2=ENABLE;
 Comment 

Using Flashback Database After Issuing an Open Resetlogs (Oracle 11g)

on August 27, 2008 at 3:02 pm
Posted In: Oracle Flashback Notes (Cat)

Suppose an error has occurred on the primary database in a Data Guard configuration in which the standby database is using real-time apply. In this situation, the same error will be applied on the standby database.

However, if Flashback Database is enabled, you can revert the primary and standby databases back to their pre-error condition by issuing the FLASHBACK DATABASE and OPEN RESETLOGS statements on the primary database, and then issuing a similar FLASHBACK STANDBY DATABASE statement on the standby database before restarting log apply services. (If Flashback Database is not enabled, you need to re-create the standby database, as described in Chapter 3 and Chapter 4, after the point-in-time recovery was performed on the primary database.)

12.5.1 Flashing Back a Physical Standby Database to a Specific Point-in-Time

The following steps describe how to avoid re-creating a physical standby database after you issued the OPEN RESETLOGS statement on the primary database.

Step 1 Determine the SCN before the RESETLOGS operation occurred.

On the primary database, use the following query to obtain the value of the system change number (SCN) that is 2 SCNs before the RESETLOGS operation occurred on the primary database:

SQL> SELECT TO_CHAR(RESETLOGS_CHANGE# - 2) FROM V$DATABASE;

Step 2 Obtain the current SCN on the standby database.

On the standby database, obtain the current SCN with the following query:

SQL> SELECT TO_CHAR(CURRENT_SCN) FROM V$DATABASE;

Step 3 Determine if it is necessary to flash back the database.

If the value of CURRENT_SCN is larger than the value of resetlogs_change# – 2, issue the following statement to flash back the standby database.

SQL> FLASHBACK STANDBY DATABASE TO SCN resetlogs_change# -2; 

If the value of CURRENT_SCN is less than the value of the resetlogs_change# – 2, skip to Step 4.

If the standby database’s SCN is far enough behind the primary database’s SCN, log apply services will be able to continue through the OPEN RESETLOGS statement without stopping. In this case, flashing back the database is unnecessary because log apply services do not stop upon reaching the OPEN RESETLOGS statement in the redo data.

Step 4 Restart Redo Apply.

To start Redo Apply on the physical standby database, issue the following statement:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT; 

The standby database is now ready to receive and apply redo from the primary database.

LOGICAL STANDBY
===============
1) On primary determine an SCN at least 2 SCN’s prior to the OPEN RESETLOGS
SELECT TO_CHAR(resetlogs_change# – 2) FROM v$DATABASE;

2) On standby, obtain the current SCN
SELECT TO_CHAR(current_scn) FROM V$DATABASE;

3) On standby flashback db
FLASHBACK STANDBY DATABASE TO SCN

4) On standby restart recovery
ALTER DATABASE START LOGICAL STANDBY APPLY IMMEDIATE;

 

 Comment 

Using Flashback Database After Issuing an Open Resetlogs Statement

on August 27, 2008 at 3:02 pm
Posted In: Oracle Data Guard Notes (Cat)

Suppose an error has occurred on the primary database in a Data Guard configuration in which the standby database is using real-time apply. In this situation, the same error will be applied on the standby database.

However, if Flashback Database is enabled, you can revert the primary and standby databases back to their pre-error condition by issuing the FLASHBACK DATABASE and OPEN RESETLOGS statements on the primary database, and then issuing a similar FLASHBACK STANDBY DATABASE statement on the standby database before restarting log apply services. (If Flashback Database is not enabled, you need to re-create the standby database, as described in Chapter 3 and Chapter 4, after the point-in-time recovery was performed on the primary database.)

12.5.1 Flashing Back a Physical Standby Database to a Specific Point-in-Time

The following steps describe how to avoid re-creating a physical standby database after you issued the OPEN RESETLOGS statement on the primary database.

Step 1 Determine the SCN before the RESETLOGS operation occurred.

On the primary database, use the following query to obtain the value of the system change number (SCN) that is 2 SCNs before the RESETLOGS operation occurred on the primary database:

SQL> SELECT TO_CHAR(RESETLOGS_CHANGE# - 2) FROM V$DATABASE;

Step 2 Obtain the current SCN on the standby database.

On the standby database, obtain the current SCN with the following query:

SQL> SELECT TO_CHAR(CURRENT_SCN) FROM V$DATABASE;

Step 3 Determine if it is necessary to flash back the database.

If the value of CURRENT_SCN is larger than the value of resetlogs_change# – 2, issue the following statement to flash back the standby database.

SQL> FLASHBACK STANDBY DATABASE TO SCN resetlogs_change# -2; 

If the value of CURRENT_SCN is less than the value of the resetlogs_change# – 2, skip to Step 4.

If the standby database’s SCN is far enough behind the primary database’s SCN, log apply services will be able to continue through the OPEN RESETLOGS statement without stopping. In this case, flashing back the database is unnecessary because log apply services do not stop upon reaching the OPEN RESETLOGS statement in the redo data.

Step 4 Restart Redo Apply.

To start Redo Apply on the physical standby database, issue the following statement:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT; 

The standby database is now ready to receive and apply redo from the primary database.

 Comment 

Flash back a Failed Primary Database to a Logical Standby Database (Oracle 11g)

on August 27, 2008 at 3:01 pm
Posted In: Oracle Flashback Notes (Cat)

Step 1 Determine the SCN to which to flash back the failed primary database.

On the new primary database, issue the following query to determine the SCN to which you want to flash back the failed primary database:

SQL> SELECT APPLIED_SCN AS FLASHBACK_SCN FROM V$LOGSTDBY_PROGRESS;

Step 2 Determine the log files that must be copied to the failed primary database for Flashback Database.

On the new primary database, issue the following query to determine the log files that must be copied to the failed primary database for Flashback Database to reach a consistent state

SQL> SELECT NAME FROM DBA_LOGSDTBY_LOG  2>   WHERE NEXT_CHANGE# >   3>           (SELECT VALUE FROM DBA_LOGSTDBY_PARAMETERS  4>   WHERE NAME = 'STANDBY_BECAME_PRIMARY_SCN') 5>           AND FIRST_CHANGE 

Step 3 Flash back the failed primary database.

To create a new logical standby database, shut down the database (if necessary), mount the failed primary database, flash it back to the FLASHBACK_SCN determined in step 1, and enable the database guard.

SQL> SHUTDOWN IMMEDIATE; SQL> STARTUP MOUNT; SQL> FLASHBACK DATABASE TO SCN became_primary_scn; SQL> ALTER DATABASE GUARD ALL;

Step 4 Open the database with the RESETLOGS option.

SQL> ALTER DATABASE OPEN RESETLOGS;

Step 5 Create a database link to the new primary database and start SQL Apply.

SQL> CREATE PUBLIC DATABASE LINK mylink 2> CONNECT TO system IDENTIFIED BY password    3> USING 'service_name_of_new_primary_database';  SQL> ALTER DATABASE START LOGICAL STANDBY APPLY NEW PRIMARY mylink; 

The role reversal is now complete.

 Comment 

Flashing Back a Failed Primary Database into a Logical Standby Database

on August 27, 2008 at 3:01 pm
Posted In: Oracle Data Guard Notes (Cat)

Step 1 Determine the SCN to which to flash back the failed primary database.

On the new primary database, issue the following query to determine the SCN to which you want to flash back the failed primary database:

SQL> SELECT APPLIED_SCN AS FLASHBACK_SCN FROM V$LOGSTDBY_PROGRESS;

Step 2 Determine the log files that must be copied to the failed primary database for Flashback Database.

On the new primary database, issue the following query to determine the log files that must be copied to the failed primary database for Flashback Database to reach a consistent state

SQL> SELECT NAME FROM DBA_LOGSDTBY_LOG  2>   WHERE NEXT_CHANGE# >   3>           (SELECT VALUE FROM DBA_LOGSTDBY_PARAMETERS  4>   WHERE NAME = 'STANDBY_BECAME_PRIMARY_SCN') 5>           AND FIRST_CHANGE <= (FLASHBACK_SCN from step 1);

Step 3 Flash back the failed primary database.

To create a new logical standby database, shut down the database (if necessary), mount the failed primary database, flash it back to the FLASHBACK_SCN determined in step 1, and enable the database guard.

SQL> SHUTDOWN IMMEDIATE; SQL> STARTUP MOUNT; SQL> FLASHBACK DATABASE TO SCN became_primary_scn; SQL> ALTER DATABASE GUARD ALL;

Step 4 Open the database with the RESETLOGS option.

SQL> ALTER DATABASE OPEN RESETLOGS;

Step 5 Create a database link to the new primary database and start SQL Apply.

SQL> CREATE PUBLIC DATABASE LINK mylink 2> CONNECT TO system IDENTIFIED BY password    3> USING 'service_name_of_new_primary_database';  SQL> ALTER DATABASE START LOGICAL STANDBY APPLY NEW PRIMARY mylink; 

The role reversal is now complete.

 Comment 

Flash back a Failed Primary Database to a Physical Standby Database (Oracle 11g)

on August 27, 2008 at 2:52 pm
Posted In: Oracle Flashback Notes (Cat)

Determine the SCN at which the old standby database became the primary database.

On the new primary database, issue the following query to determine the SCN at which the old standby database became the new primary database:

SQL> SELECT TO_CHAR(STANDBY_BECAME_PRIMARY_SCN) FROM V$DATABASE;

Step 2 Flash back the failed primary database.

To create a new physical standby database, shut down the old primary database (if necessary), mount it, and flash it back to the value for STANDBY_BECAME_PRIMARY_SCN that was determined in Step 1:

SQL> SHUTDOWN IMMEDIATE; SQL> STARTUP MOUNT; SQL> FLASHBACK DATABASE TO SCN standby_became_primary_scn;

Step 3 Convert the database to a physical standby database.

Perform the following steps on the old primary database:

  1. Issue the following statement on the old primary database:
  2. SQL> ALTER DATABASE CONVERT TO PHYSICAL STANDBY; 

    This statement will dismount the database after successfully converting the control file to a standby control file.

  3. Shut down and restart the database:
SQL> SHUTDOWN IMMEDIATE; SQL> STARTUP MOUNT;

Step 4 Restart transporting redo to the new physical standby database.

Step 5 Start Redo Apply.

Start Redo Apply or real-time apply on the new physical standby database:

To start Redo Apply:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT; 

To start real-time apply:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE    2> USING CURRENT LOGFILE DISCONNECT; 
 Comment 

Flashing Back a Failed Primary Database into a Physical Standby Database

on August 27, 2008 at 2:52 pm
Posted In: Oracle Data Guard Notes (Cat)

Determine the SCN at which the old standby database became the primary database.

On the new primary database, issue the following query to determine the SCN at which the old standby database became the new primary database:

SQL> SELECT TO_CHAR(STANDBY_BECAME_PRIMARY_SCN) FROM V$DATABASE;

Step 2 Flash back the failed primary database.

To create a new physical standby database, shut down the old primary database (if necessary), mount it, and flash it back to the value for STANDBY_BECAME_PRIMARY_SCN that was determined in Step 1:

SQL> SHUTDOWN IMMEDIATE; SQL> STARTUP MOUNT; SQL> FLASHBACK DATABASE TO SCN standby_became_primary_scn;

Step 3 Convert the database to a physical standby database.

Perform the following steps on the old primary database:

  1. Issue the following statement on the old primary database:
  2. SQL> ALTER DATABASE CONVERT TO PHYSICAL STANDBY; 

    This statement will dismount the database after successfully converting the control file to a standby control file.

  3. Shut down and restart the database:
SQL> SHUTDOWN IMMEDIATE; SQL> STARTUP MOUNT;

Step 4 Restart transporting redo to the new physical standby database.

Step 5 Start Redo Apply.

Start Redo Apply or real-time apply on the new physical standby database:

To start Redo Apply:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT; 

To start real-time apply:

SQL> ALTER DATABASE RECOVER MANAGED STANDBY DATABASE    2> USING CURRENT LOGFILE DISCONNECT; 
 Comment 

Roll Back After Unsuccessful Switchover and Start Over

on August 27, 2008 at 2:29 pm
Posted In: Oracle Data Guard Notes (Cat)

This MIGHT work !

ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY;

If successful then shutdown and startup

ELSE

When the switchover to change the role from primary to physical standby was

initiated, a trace file was written in the log directory. This trace file contains the

SQL statements required to re-create the original primary control file. Locate the

trace file and extract the SQL statements into a temporary file. Execute the

temporary file from SQL*Plus. This will revert the new standby database back to

the primary role.

3. shutdown original standby

4. Create a new standby control file. This is necessary to resynchronize the primary

database and physical standby database. Copy the physical standby control file to

the original physical standby system. Section 3.2.2 describes how to create a

physical standby control file.

5. Restart the original physical standby instance.

If this procedure is successful and archive gap management is enabled, the FAL

processes will start and re-archive any missing archived redo log files to the

physical standby database. Force a log switch on the primary database and

examine the alert logs on both the primary database and physical standby

database to ensure the archived redo log file sequence numbers are correct.

See Section 5.8 for information about archive gap management and Appendix G

for information about locating the trace files.

6. Try the switchover again.

At this point, the Data Guard configuration has been rolled back to its initial state,

and you can try the switchover operation again (after correcting any problems that

might have led to the initial unsuccessful switchover).

 

 

 

 Comment 

switchover fails

on August 27, 2008 at 2:25 pm
Posted In: Oracle Data Guard Notes (Cat)

Ensure all archive is present.

Ensure recovery in progress.

Check switchover status again – should be ok

SELECT SWITCHOVER_STATUS FROM V$DATABASE;

to primary

IF SESSIONS ACTIVE then error is:

ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY *

ORA-01093: ALTER DATABASE CLOSE only permitted with no sessions connected

—

SELECT SID, PROCESS, PROGRAM FROM V$SESSION WHERE TYPE = ‘USER’ AND SID <> (SELECT DISTINCT SID FROM V$MYSTAT);

if example shows jobs (i.e. CJQ0 is present) then

SHOW PARAMETER JOB_QUEUE_PROCESSES;

ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;

If still errors then:

SELECT SID, PROCESS, PROGRAM FROM V$SESSION;

Kill the sessions.

 

 Comment 

Failover a standby database

on August 27, 2008 at 2:19 pm
Posted In: Oracle Data Guard Notes (Cat)

Check archive log gaps

SELECT THREAD#, LOW_SEQUENCE#, HIGH_SEQUENCE# FROM V$ARCHIVE_GAP;

ALTER DATABASE REGISTER PHYSICAL LOGFILE ‘filespec1‘;

ALTER DATABASE RECOVER MANAGED STANDBY DATABASE FINISH FORCE;

ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY;

ALTER DATABASE OPEN; OR SHUTDOWN IMMEDIATE and STARTUP;

 

 Comment 

switchover a standby database

on August 27, 2008 at 2:16 pm
Posted In: Oracle Data Guard Notes (Cat)

SELECT SWITCHOVER_STATUS FROM V$DATABASE;

to standby /* NOT – SESSIONS ACTIVE */

ALTER DATABASE COMMIT TO SWITCHOVER TO PHYSICAL STANDBY;

SHUTDOWN IMMEDIATE;

STARTUP MOUNT

SELECT SWITCHOVER_STATUS FROM V$DATABASE;

to primary

ALTER DATABASE COMMIT TO SWITCHOVER TO PRIMARY;

SHUTDOWN IMMEDIATE; /* or */ ALTER DATABASE OPEN;

STARTUP

ALTER SYSTEM SWITCH LOGFILE;

 

 

 Comment 

manual standby file management

on August 27, 2008 at 2:09 pm
Posted In: Oracle Data Guard Notes (Cat)

Query the V$DATAFILE view. For example:

SQL> SELECT NAME FROM V$DATAFILE;

::::::::::::

/dev/raw/raw100

/u01/app/oracle/product/10.1.0/dbs/UNNAMED00007

ALTER SYSTEM SET STANDBY_FILE_MANAGEMENT=MANUAL;

ALTER DATABASE CREATE DATAFILE ‘/u01/app/oracle/product/10.1.0/dbs/UNNAMED00007’

AS ‘/dev/raw/raw101’;

ALTER SYSTEM SET STANDBY_FILE_MANAGEMENT=AUTO;

RECOVER MANAGED STANDBY DATABASE DISCONNECT;

Recovery should continue.

 Comment 

Opening standby for read only AND read/write

on August 27, 2008 at 2:04 pm
Posted In: Oracle Data Guard Notes (Cat)

ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL;

ALTER DATABASE OPEN;

 

ALTER DATABASE RECOVER MANAGED STANDBY DATABASE DISCONNECT FROM SESSION;

OR to enable real-time apply, include the USING CURRENT LOGFILE clause:

ALTER DATABASE RECOVER MANAGED STANDBY DATABASE USING CURRENT LOGFILE;

 

 

 Comment 

rman restore for netbackup

on July 31, 2008 at 10:01 am
Posted In: Oracle Rman Notes (Cat)

run {

set until time “to_date(’23 jan 2008 10:11:00′,’dd mon yyyy hh24:mi:ss’)”;

allocate channel ch00 type ‘SBT_TAPE’;

send ‘NB_ORA_CLIENT=host_name’;

set command id to ‘RMAN_DATABASE_RESTORE’;

restore database;

recover database;

}

 Comment 

how to use datapump expdp impdp

on July 31, 2008 at 9:23 am
Posted In: Oracle odds and ends (Cat)

Using flat files

Create the directories

SQL> CREATE DIRECTORY dpump_dir1 AS ‘/usr/apps/datafiles’;

SQL> GRANT READ, WRITE ON DIRECTORY dpump_dir1 TO hr;

SQL> CREATE DIRECTORY DUMP_FILES1 AS ‘/usr/apps/dumpfiles1’;

$ setenv DATA_PUMP_DIR DUMP_FILES1

$ expdp hr/hr TABLES=employees DUMPFILE=employees.dmp

SQL> SELECT directory_name, directory_path FROM dba_directories WHERE directory_name=’DATA_PUMP_DIR’;


DEFAULT DIRECTORY =
$ORACLE_HOME/rdbms/log/


Using ASM

SQL> CREATE or REPLACE DIRECTORY dpump_dir as ‘+DATAFILES/’;

SQL> CREATE or REPLACE DIRECTORY dpump_log as ‘/homedir/user1/’;

SQL> GRANT READ, WRITE ON DIRECTORY dpump_dir TO hr;

SQL> GRANT READ, WRITE ON DIRECTORY dpump_log TO hr;

$ expdp hr/hr DIRECTORY=dpump_dir DUMPFILE=hr.dmp LOGFILE=dpump_log:hr.log

 

 

 

 

 

 

 Comment 

table stats using table TRACE_INFO

on June 23, 2008 at 1:32 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

–tab_all_stats
— mdw 30/11/04
— show the stats for a table, it’s columns, it’s indexes…
set veri off pages 64 pause off lines 100
col owner         form A8
col table_name    form A14 word wrap
col avg_sp        form 9,999
col avg_l         form 9999
col avg_sp        form 9,999
col n_buck        form 9,999
col chain         form 9,999
col clustf         form 999,999
col bl            form 999
col blocks        form 999,999
col low_v         form a10 trunc
col hi_v          form a10 trunc
col num_rows      form 99999,999
col dist_keys     form 99999,999
col l_blks        form 99999,999
col num_nulls     form 99,999
col column_name   form a20 word wrap
col index_name    form a15 word wrap
col buckno        form 99,999,999,999
col end_val       form 9,999,999,999,999
col end_act_val   form A10

select owner
, table_name
, num_rows
, blocks
, avg_space   avg_sp
, chain_cnt   chain
, avg_row_len avg_l
, global_stats  gls
, user_stats    uls
, to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
, sample_size   samp_size
from dba_tables
where table_name = ‘TRACE_INFO’
/
select index_name
,substr(index_type,1,3)   typ
,substr(uniqueness,1,3)   unq
,blevel                   bl
,leaf_blocks              l_blks
,distinct_keys            dist_keys
,clustering_factor        clustf
,avg_leaf_blocks_per_key  lb_key
,avg_data_blocks_per_key  db_key
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
from dba_indexes
where table_name = ‘TRACE_INFO’
/
—
select– owner
–,table_name
column_name
,num_distinct
,low_value    low_v
,high_value   hi_v
,num_nulls    n_nulls
,num_buckets  n_buck
,avg_col_len  avg_l
from dba_tab_columns
where table_name = ‘TRACE_INFO’
order by column_id
/
select
column_name
,endpoint_value  end_val
,endpoint_number buckno
,endpoint_actual_value  end_act_val
from all_tab_histograms
where table_name = ‘TRACE_INFO’
order by table_name,column_name,endpoint_number
/
—
clear colu

 Comment 

tablespace info by ts name and object_type from dba_segments

on June 23, 2008 at 1:32 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— ts_objs_by_size
— mdw 20/10/97
— summary of contents of a tablespace
set pause on
set pages 24
clear breaks
col segment_name  form a20 word wrap
col ts_name       form a8 word wrap
col owner         form a8 word wrap
break on ts_name skip 1 on owner nodup
spool ts_objs_by_size.lst
select tablespace_name                            ts_name
      ,owner                                      owner
      ,rtrim(segment_name||’ ‘||partition_name)   segment_name
      ,substr(segment_type,1,7)                   typ
      ,to_char(extents,’9,999′)                   extents
      ,to_char(initial_extent/1024,’9,999,999′)   initial_K
      ,to_char(next_extent/1024,’9,999,999′)      next_k
from sys.dba_segments
where tablespace_name like upper(nvl(‘&ts_name’,’whoops’)||’%’) and segment_type like upper(nvl(‘&obj_type’,’TAB’)||’%’)
order by 1, blocks desc, 3
/
spool off
clear breaks
clear columns

 Comment 

tablespace info from dba_segments and dba_objects

on June 23, 2008 at 1:32 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— ts_conts
— mdw 20/10/97
— summary of contents of a tablespace
set pause on
set pages 24
set lines 90
clear breaks
col segment_name  form a22 word wrap
col ts_name       form a8 word wrap
col owner         form a8 word wrap
break on ts_name skip 1 on owner nodup
spool ts_conts.lst
select ds.tablespace_name                               ts_name
      ,ds.owner                                         owner
      ,rtrim(ds.segment_name||’ ‘||ds.partition_name)   segment_name
      ,substr(ds.segment_type,1,7)                      typ
      ,to_char(ds.extents,’999′)                        exts
      ,to_char(ds.initial_extent/1024,’9,999,999′)      initial_K
      ,to_char(ds.next_extent/1024,’9999,999′)          next_k
      ,to_char(ds.bytes/1024,’999,999,999′)             size_k
      ,do.created                                       created
      ,do.last_ddl_time                                 last_ddl_time
from sys.dba_segments ds, sys.dba_objects do
where ds.tablespace_name like upper(nvl(‘&ts_name’,’whoops’)||’%’) and do.object_name = ds.segment_name
order by 1,2,4 desc,3
/
set lines 80
spool off
clear breaks
clear columns

 Comment 

tablespace info from dba_segments

on June 23, 2008 at 1:31 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— ts_conts
— mdw 20/10/97
— summary of contents of a tablespace
set pause on
set pages 24
set lines 90
clear breaks
col segment_name  form a22 word wrap
col ts_name       form a8 word wrap
col owner         form a8 word wrap
break on ts_name skip 1 on owner nodup
spool ts_conts.lst
select tablespace_name                            ts_name
      ,owner                                      owner
      ,rtrim(segment_name||’ ‘||partition_name)   segment_name
      ,substr(segment_type,1,7)                   typ
      ,to_char(extents,’999′)                     exts
      ,to_char(initial_extent/1024,’9,999,999′)   initial_K
      ,to_char(next_extent/1024,’9999,999′)       next_k
     ,to_char(bytes/1024,’999,999,999′)           size_k
from sys.dba_segments
where tablespace_name like upper(nvl(‘&ts_name’,’whoops’)||’%’)
order by 1,2,4 desc,3
/
set lines 80
spool off
clear breaks
clear columns

 Comment 

sum size of tablespace datafiles and free space.sql

on June 23, 2008 at 1:31 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— spc_sum
— select summary of size of ts datafiles and free space
col sum_k      form 999,999,999
col sum_blks   form 99,999,999
col max_chnk_k form 99,999,999
col ts_name    form a20        word wrap
col num_chnk   form 999,999
break on ts_name nodup
set pause on
set pages 32 trimspool on
accept v_ts char prompt ‘Enter the tablespace (or leave null)> ‘
spool spc_sum.lst
select ddf.tablespace_name ts_name
      ,’alloc’             ord
      ,sum(ddf.blocks)     sum_blks
      ,sum(ddf.bytes/1024) sum_k
      ,max(ddf.bytes/1024) max_chnk_k
      ,count(*)            num_chnk
from dba_data_files ddf
where tablespace_name like upper(nvl(‘&v_ts’,’%’))||’%’
group by tablespace_name
union
select dfs.tablespace_name ts_name
      ,’free’              ord
      ,sum(dfs.blocks)     sum_blks
      ,sum(dfs.bytes/1024) sum_k
      ,max(dfs.bytes/1024) max_chnk_k
      ,count(*)            num_chnk
from dba_free_space dfs
where tablespace_name like upper(nvl(‘&v_ts’,’%’))||’%’
group by tablespace_name
order by ts_name,ord
/
spool off
clear colu
— EOF

 Comment 

sum blocks used by schema.sql

on June 23, 2008 at 1:30 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— a summary of blocks allocated to individual schemas
prompt blocks used(well, allocated) per user
spool blocks_by_usr.lst
col sumblocks form 999,999,999
select owner, sum(blocks) sumblocks from dba_segments where segment_type like ‘TAB%’ and owner like upper(‘&owner’)||’%’ group by owner order by sum(blocks)
/
spool off
clear colu

 Comment 

size of the db in different ways.sql

on June 23, 2008 at 1:30 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

— schema_size_sum.sql
— mdw 17/10/05
— summary of the size of the database (as measured in all sorts of ways)
set pages 32
set pause off
col total_dbf_mb form 999,999,999
col dat_dbf_mb form 999,999,999
col ind_dbf_mb form 999,999,999
col total_seg_mb form 999,999,999
col table_seg_mb form 999,999,999
col index_seg_mb form 999,999,999
col LOB_seg_mb form 999,999,999
spool schema_size_sum.lst
select owner,sum(bytes/(1024*1024)) total_seg_MB
from dba_segments
where segment_type not in (‘TEMPORARY’,’ROLLBACK’,’CACHE’)
and owner not in (‘SYS’,’SYSTEM’)
group by owner
order by owner
/
select owner,sum(bytes/(1024*1024)) table_seg_MB
from dba_segments
where segment_type in (‘TABLE’,’TABLE PARTITION’)
and owner not in (‘SYS’,’SYSTEM’)
group by owner
order by owner
/
select owner,sum(bytes/(1024*1024)) index_seg_MB
from dba_segments
where segment_type in (‘INDEX’,’INDEX PARTITION’)
and owner not in (‘SYS’,’SYSTEM’)
group by owner
order by owner
/
select owner,sum(bytes/(1024*1024)) LOB_seg_MB
from dba_segments
where segment_type in (‘LOBINDEX’,’LOBSEGMENT’,’LOB PARTITION’)
and owner not in (‘SYS’,’SYSTEM’)
group by owner
order by owner
/
–where cole like nvl(upper(‘ampersand’),’WHOOPS’)||’%’
spool off
clear col
—
— EOF
—

 Comment 

simple list of constraints on a table.sql

on June 23, 2008 at 1:30 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— cons_lst.sql
— mdw 7/97 – simple list of constraints on a table
set pause on
set pages 24
set pause ‘Any Key>’
spool cons_lst.lst
select owner
,table_name    tab_nam
,constraint_type  const_type
,constraint_name  const_name
from all_constraints
where table_name like upper(‘&tab_name’||’%’)
and constraint_name not like ‘SYS%’
/
spool off
—

 Comment 

show what tables are locked by what process.sql

on June 23, 2008 at 1:30 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

REM reports what tables are locked by what processes

set pagesize 80;
set linesize 200;

column db_user format A20;
column db_table format A32;
column program format A35;
column lock_mode format A15;

PROMPT Current locks:
select a.osuser||’@’||a.machine db_user,a.program,c.object_name db_table,decode(b.locked_mode,3,’Shared’,5,’Exclusive’,b.locked_mode) lock_mode
from v$session a, v$locked_object b, all_objects c
where
a.type = ‘USER’ and
c.object_type = ‘TABLE’ and
a.sid = b.session_id and
b.object_id = c.object_id;

PROMPT Alternative view of (probably the same) locks:

select a.osuser||’@’||a.machine db_user,b.ctime seconds,decode(b.lmode,2,’Row share’,3,’Row exclusive’,4,’Table share’,6,’Table exclusive’,b.lmode) lock_mode
from v$session a,v$lock b
where
a.sid = b.sid and
a.type = ‘USER’;

 Comment 

show view text.sql

on June 23, 2008 at 1:29 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

set long 32767
set pages 500
set pause on
set trimspool on
set pause ‘Any Key…>’
spool vw_txt.lst
select owner, view_name, text_length, text
from dba_views
where view_name like upper (nvl(‘&vw_name’,’WHOOPS’)||’%’)
/
set long 80
spool off
—
— End of File
—

 Comment 

show uga and pga memory usage by all sessions.sql

on June 23, 2008 at 1:29 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

—
— This Query displays full PGA and UGA memory info for all sessions.
—
— Oracle 10g version.
—

select decode(nvl(length(z.username),0),
              0,
              substr(z.PROGRAM,instr(z.program,'(‘),20),
              substr(z.username,1,20)) “Username”,
       substr(to_char(z.sid),1,4) “SID”,
       s_pga.pga “PGA”,
       s_pgam.pgam “PGA Max”,
       (s_pgam.pgam – s_pga.pga) “PGA Diff”,
       s_uga.uga “UGA”,
       s_ugam.ugam “UGA Max”,
       (s_ugam.ugam – s_uga.uga) “UGA Diff”,
       s_tota.tota “(UGA + PGA)”,
       ((s_ugam.ugam – s_uga.uga) + (s_pgam.pgam – s_pga.pga)) “(UGA + PGA) Diff”
from (select b.sid, b.value uga
      from
       v$sesstat b
      where
       b.statistic# = 20) s_uga,
     (select b.sid, b.value ugam
      from
       v$sesstat b
      where
       b.statistic# = 21) s_ugam,
     (select b.sid, b.value pga
      from
       v$sesstat b
      where
       b.statistic# = 25) s_pga,
     (select b.sid, b.value pgam
      from
       v$sesstat b
      where
       b.statistic# = 26) s_pgam,
     (select b.sid, sum(b.value) tota
      from
       v$sesstat b
      where
       b.statistic# in (20,25)
      group by b.sid) s_tota,
       v$session z
where z.sid = s_uga.sid and
      z.sid = s_pga.sid and
      z.sid = s_tota.sid and
      z.sid = s_ugam.sid and
      z.sid = s_pgam.sid
union
select ‘** TOTALS **’,
       substr(‘Count = ‘ || to_char(count(z.sid)),1,15),
       sum(s_pga.pga) “PGA”,
       sum(s_pgam.pgam) “PGA Max”,
       sum(s_pgam.pgam – s_pga.pga) “PGA Diff”,
       sum(s_uga.uga) “UGA”,
       sum(s_ugam.ugam) “UGA Max”,
       sum(s_ugam.ugam – s_uga.uga) “UGA Diff”,
       sum(s_tota.tota) “(UGA + PGA)”,
       sum((s_ugam.ugam – s_uga.uga) + (s_pgam.pgam – s_pga.pga)) “(UGA + PGA) Diff”
from (select b.sid, b.value uga
      from
       v$sesstat b
      where
       b.statistic# = 20) s_uga,
     (select b.sid, b.value ugam
      from
       v$sesstat b
      where
       b.statistic# = 21) s_ugam,
     (select b.sid, b.value pga
      from
       v$sesstat b
      where
       b.statistic# = 25) s_pga,
     (select b.sid, b.value pgam
      from
       v$sesstat b
      where
       b.statistic# = 26) s_pgam,
     (select b.sid, sum(b.value) tota
      from
       v$sesstat b
      where
       b.statistic# in (20,25)
      group by b.sid) s_tota,
       v$session z
where z.sid = s_uga.sid and
      z.sid = s_pga.sid and
      z.sid = s_tota.sid and
      z.sid = s_ugam.sid and
      z.sid = s_pgam.sid
order by 4 desc
/

 Comment 

show text for a package.sql

on June 23, 2008 at 1:28 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

–pkg_txt.sql
— mdw 7/97
— pull out text for a package.
set long 64000
set pages 1000
set trims on
set lines 79
set pause on
set array 1
set pause ‘Any Key…>’
spool pkg_txt.lst
SELECT TEXT
FROM SYS.DBA_SOURCE
WHERE (TYPE = ‘PACKAGE BODY’
or type = ‘PROCEDURE’
or type = ‘FUNCTION’)
AND NAME LIKE UPPER(NVL(‘&PKG_NAME’,’ERIC’)||’%’)
ORDER BY name,owner,LINE
/
spool off
set pages 40
—

 Comment 

show structure of indexes on a table.sql

on June 23, 2008 at 1:28 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

REM Script to show the structure of all indexes on a specified table
REM to assist in SQL tuning

set pages 500;
set lines 100;
set feed off;
set arraysize 1;
set verify off;

column column_name format A30;
break on INDEX_NAME;

accept tablename prompt ‘Table name: ‘

select
a.index_name,b.column_name,b.column_position
from user_indexes a,user_ind_columns b
where
a.index_name = b.index_name and
a.table_name = ‘&tablename’
order by a.index_name,b.column_position;

set feed on;

 

 Comment 

show sessions logged on.sql

on June 23, 2008 at 1:28 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

— show_sess.sql
— mdw 03/09/02
— summary of sessions logged on
set pages 32
set pause on
accept bground char prompt ‘ignore background (Yy)?> ‘
col sid      form 999
col username form a10 word wrap head user/pid
col osuser   form a8 word wrap
col program  form a20 word wrap
col machine  form a12 word wrap
col logon    form a13
spool show_sess.lst
select sid
      ,nvl(username,process) username
      ,osuser
      ,substr(server,1,3) svr
      ,program||’ ‘||module  program
      ,machine
      ,to_char(logon_time,’ddmm hh24:mi:ss’) logon
from v$session
where type != decode (upper(‘&bground’),’Y’,’BACKGROUND’
                                       ,    ‘ERIC’)
order by sid
/
spool off
clear col
—
— EOF
—

 Comment 

DELETE show sessions logged on.sql

on June 23, 2008 at 1:27 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

— show_sess.sql
— mdw 03/09/02
— summary of sessions logged on
set pages 32
set pause on
accept bground char prompt ‘ignore background (Yy)?> ‘
col sid      form 999
col username form a10 word wrap head user/pid
col osuser   form a8 word wrap
col program  form a20 word wrap
col machine  form a12 word wrap
col logon    form a13
spool show_sess.lst
select sid
      ,nvl(username,process) username
      ,osuser
      ,substr(server,1,3) svr
      ,program||’ ‘||module  program
      ,machine
      ,to_char(logon_time,’ddmm hh24:mi:ss’) logon
from v$session
where type != decode (upper(‘&bground’),’Y’,’BACKGROUND’
                                       ,    ‘ERIC’)
order by sid
/
spool off
clear col
—
— EOF
—

 Comment 

show segment space used by an object.sql

on June 23, 2008 at 1:26 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

— obj_size.sql
— mdw 10/03/97
— show current allocated space for (by default tables) specifed objects
— mdw 24/04/01
— adding in the checking of user to look at – sanger uses multiple schemas
—
clear break
break on o_type nodup on owner nodup on obj_name nodup skip 1 on tablespace nodup
set veri off
set pause on
set pages 24
set lines 80
col o_type form a8 truncate
col owner form a8 word wrap
col obj_name form a22 word wrap
col tablespace form a14 word wrap
— mdw temp change to spool file
spool obj_siz.lst
select segment_type                                 o_type
      ,owner                                        owner
      ,segment_name||’ ‘||partition_name            obj_name
      ,tablespace_name                              tablespace
      ,substr(extent_id,1,3)                        num
      ,substr(to_char(bytes/1024,’99,999,999′),1,11) K_bytes                 
      ,substr(to_char(blocks,’999,999′),1,8)        blocks
from sys.dba_extents
where segment_name like upper(nvl(‘&nme’,’WHOOPS’)||’%’)
and   segment_type like upper(nvl(‘&typ’,’TABLE’)||’%’)
and   owner like upper(nvl(‘&own’,user)||’%’)
order by 1,2,3,5
/
clear colu
spool off

 Comment 

show privs on an object.sql

on June 23, 2008 at 1:26 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— obj_privs.sql
— mdw 09/11/01
— Hard tho it is to believe, I had no script to show privs on an obj
— so wrote one now.
col grantee form a12 word wrap
col owner form a12 word wrap
col table_name form a22 word wrap
col grantor form a12 word wrap
col privilege form a12 word wrap
col grantable form a3
spool obj_grnats.lst
select grantee
,owner
,table_name
,grantor
,privilege
,grantable
from dba_tab_privs
where table_name like upper(nvl(‘&obj_name’,’WHOOPS’))||’%’
and  owner like upper(‘&obj_own’)||’%’
order by table_name,owner
/
spool off
clear colu

 Comment 

show partition table structures.sql

on June 23, 2008 at 1:25 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

REM Script to show the structure of partitioned tables

set pages 500;
set lines 300;
set feed off;

–column table_name noprint;
column partition_position noprint;
column high_value format A20;

column partition_name format A22;
column tablespace_name format A15;
column fl format 99;
column flg format 99;

prompt ===================================================================================================

prompt Partitioned tables: general layout

select
table_name,partition_position,partition_name,
tablespace_name,high_value,pct_free,initial_extent,
freelists fl, freelist_groups flg,logging
from dba_tab_partitions
order by table_name,partition_position;

prompt ===================================================================================================

prompt Partitioned tables: usage stats

select
a.table_name,a.partition_position,a.partition_name,
a.num_rows,a.avg_space,a.blocks,a.empty_blocks,a.chain_cnt,
b.extents
–,a.last_analyzed
from dba_tab_partitions a, dba_segments b
where
a.table_owner = b.owner and
a.partition_name = b.partition_name and
a.table_name = b.segment_name
order by table_name,partition_position;

prompt ===================================================================================================

set feed on;

 Comment 

show partition table column statistics.sql

on June 23, 2008 at 1:25 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— part_col_stats
— mdw 21/03/2003
— more detailed info on cols
col owner            form a6 word wrap
col table_name       form a10 word wrap
col partition_name   form a10 word wrap
col column_name      form a22 word wrap
col num_vals         form 999,999,999
col dnsty            form 0.9999
col num_nulls        form 999,999,999
col avg_l            form 9,999
break on owner nodup on table_name nodup on partition_name nodup
set lines 100
spool part_col_counts.lst
select owner
      ,table_name
      ,partition_name
      ,column_name
      ,num_distinct num_vals
      ,num_nulls
      ,density dnsty
      ,avg_col_len avg_l
from dba_part_col_statistics
where owner            like upper(‘&tab_own’||’%’)
and   table_name       like upper(nvl(‘&tab_name’,’WHOOPS’)||’%’)
and   partition_name   like upper(‘&part_name’||’%’)
and   column_name      like upper(‘&col_name’||’%’)
ORDER BY 1,2,3,4
/
clear colu
spool off
clear breaks
set lines 80

 Comment 

show partition index structure.sql

on June 23, 2008 at 1:25 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

REM Script to show the structure of partitioned indices

set pages 500;
set lines 200;
set feed off;

–column index_name noprint;
column partition_position noprint;
column high_value format A20;

column partition_name format A22;
column tablespace_name format A15;
column fl format 99;
column flg format 99;

prompt ===================================================================================================

prompt Partitioned indices: general layout

select
index_name,partition_position,partition_name,
tablespace_name,high_value,pct_free,initial_extent,
freelists fl, freelist_groups flg,logging
from dba_ind_partitions
order by index_name,partition_position;

prompt ===================================================================================================

prompt Partitioned indices: usage stats

select
a.index_name,a.partition_position,a.partition_name,
a.num_rows,
b.blocks,b.extents,a.last_analyzed
from dba_ind_partitions a, dba_segments b
where
a.index_owner = b.owner and
a.partition_name = b.partition_name
order by index_name,partition_position;

prompt ===================================================================================================

set feed on;

 

 Comment 

show object dependencies.sql

on June 23, 2008 at 1:24 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

set pages 32
set pause on
spool obj_dep.lst
select * from dba_dependencies where referenced_name like nvl(upper(‘&obj_name’||’%’),’WHOOPS’)
/
spool off
clear col

 Comment 

show logon_time username machine and locks for sessions.sql

on June 23, 2008 at 1:24 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

set verify off

break on Username on report
compute count of Username on Username

set linesize 180
set pagesize 9999

SELECT  UNIQUE RPAD(TO_CHAR(A.LOGON_TIME,’DD-MM-YY:HH24.MI’),16) LOGON_TIME,
rpad(A.USERNAME,10)username,rpad(A.OSUSER,6)osuser,rpad(A.MACHINE,20)machine,rpad(A.PROGRAM,25)program,
rpad(C.OBJECT_NAME,30)object,rpad(C.OBJECT_TYPE,10)obtype 
FROM  V$SESSION A, V$LOCKED_OBJECT B, ALL_OBJECTS C
WHERE  A.TYPE   = ‘USER’
AND  A.SID   = B.SESSION_ID
AND  B.OBJECT_ID  = C.OBJECT_ID;

 Comment 

show grants.sql

on June 23, 2008 at 1:24 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

column obj format A35;
column grantor format A20;
column privilege format A15;
column grantee format A20;

set pagesize 80;

select grantee,owner||’.’||table_name obj,privilege from dba_tab_privs
where grantor = upper(‘&grantor’)
order by grantee,obj;

 

 Comment 

show general stats for a table.sql

on June 23, 2008 at 1:23 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

–tab_stats
— mdw 22/12/04
— show the stats for a table,  it’s indexes…
set veri off pages 64 pause off lines 100
accept tabname prompt ‘Name for Table: ‘
col owner         form A10
col table_name    form A14 word wrap
col avg_sp        form 9,999
col avg_l         form 9,999
col avg_sp        form 9,999
col lb_key        form 99,999
col db_key        form 99,999
col chain         form 9,999
col clustf         form 9999,999
col bl            form 999
col blocks        form 999,999
col low_v         form a10 trunc
col hi_v          form a10 trunc
col num_rows      form 99999,999
col dist_keys     form 99999,999
col l_blks        form 99999,999
col samp_size     form 99999,999
col column_name   form a15 word wrap
col index_name    form a15 word wrap
spool tab_stats.lst
select owner
,table_name
,num_rows
,blocks
,avg_space   avg_sp
,chain_cnt   chain
,avg_row_len avg_l
,global_stats  gls
,user_stats    uls
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
,sample_size  samp_size
from dba_tables
where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
/
select index_name
,substr(index_type,1,3)   typ
,substr(uniqueness,1,3)   unq
,blevel                   bl
,leaf_blocks              l_blks
,distinct_keys            dist_keys
,clustering_factor        clustf
,avg_leaf_blocks_per_key  lb_key
,avg_data_blocks_per_key  db_key
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
,sample_size  samp_size
from dba_indexes
where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
/
set pause on
—
—
clear colu
spool off

 Comment 

show general stats for a table Another view .sql

on June 23, 2008 at 1:23 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

–tab_info
— mdw 30/11/04
— show the stats and info for a table, it’s coulns, it’s indexes…
set veri off pages 64 pause off
accept tabname prompt ‘Name for Table: ‘
col owner         form A8
col ind_owner     form A8
col table_name    form A14 word wrap
col avg_sp        form 9,999
col avg_l         form 9,999
col avg_sp        form 9,999
col chain         form 9,999
col clustf         form 9,999
col bl            form 999
col blocks        form 999,999
col low_v         form a10 trunc
col hi_v          form a10 trunc
col num_rows      form 99999,999
col dist_keys     form 99999,999
col l_blks        form 99999,999
col num_nulls     form 99,999
col column_name   form a15 word wrap
spool tab_info.lst
select owner
,table_name
,num_rows
,blocks
,avg_space   avg_sp
,chain_cnt   chain
,avg_row_len avg_l
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
,global_stats  gls
,user_stats    uls
from dba_tables
where table_name like upper(nvl(‘&&tabname’,’eric’))
/
set pause on
—
select– owner
–,table_name
column_name
,num_distinct
,low_value    low_v
,high_value   hi_v
,num_nulls    n_nulls
,num_buckets  n_buck
,avg_col_len  avg_l
from dba_tab_columns
where table_name like upper(nvl(‘&&tabname’,’eric’))
order by column_id
/
—
col ind_name form a18 wrap
col tab_name form a18 wrap
col col_name form a20 wrap
break on ind_owner nodup on ind_name nodup on tab_name skip 1
 select
 INDEX_OWNER                 ind_owner
,INDEX_NAME                  ind_Name
,TABLE_NAME                  tab_Name
,substr(column_position,1,3) Psn
,COLUMN_NAME                 Col_Name
from all_ind_columns
where table_name like upper(nvl(‘&&tabname’,’WHOOPS’))
order by 3,1,2,4,5
/
—
clear colu
spool off

 Comment 

show general stats for a table again again.sql

on June 23, 2008 at 1:23 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

–tab_all_stats
— mdw 30/11/04
— show the stats for a table, it’s coulns, it’s indexes…
set veri off pages 64 pause off lines 100
accept tabname prompt ‘Name for Table: ‘
col owner         form A8
col table_name    form A14 word wrap
col avg_sp        form 9,999
col avg_l         form 9999
col avg_sp        form 9,999
col n_buck        form 9,999
col chain         form 9,999
col clustf         form 999,999
col bl            form 999
col blocks        form 999,999
col low_v         form a10 trunc
col hi_v          form a10 trunc
col num_rows      form 99999,999
col dist_keys     form 99999,999
col l_blks        form 99999,999
col num_nulls     form 99,999
col column_name   form a20 word wrap
col index_name    form a15 word wrap
col buckno        form 99,999,999,999
col end_val       form 9,999,999,999,999
col end_act_val   form A10
spool tab_all_stats.lst
select owner
,table_name
,num_rows
,blocks
,avg_space   avg_sp
,chain_cnt   chain
,avg_row_len avg_l
,global_stats  gls
,user_stats    uls
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
,sample_size   samp_size
from dba_tables
where table_name = upper(nvl(‘&&tabname’,’eric’))
–where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
/
select index_name
,substr(index_type,1,3)   typ
,substr(uniqueness,1,3)   unq
,blevel                   bl
,leaf_blocks              l_blks
,distinct_keys            dist_keys
,clustering_factor        clustf
,avg_leaf_blocks_per_key  lb_key
,avg_data_blocks_per_key  db_key
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
from dba_indexes
where table_name = upper(nvl(‘&&tabname’,’eric’))
–where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
/
set pause on
—
select– owner
–,table_name
column_name
,num_distinct
,low_value    low_v
,high_value   hi_v
,num_nulls    n_nulls
,num_buckets  n_buck
,avg_col_len  avg_l
from dba_tab_columns
where table_name = upper(nvl(‘&&tabname’,’eric’))
–where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
order by column_id
/
select
column_name
,endpoint_value  end_val
,endpoint_number buckno
,endpoint_actual_value  end_act_val
from all_tab_histograms
where table_name = upper(nvl(‘&tabname’,’WHOOPS’))
–where table_name like upper(nvl(‘&tabname’,’WHOOPS’)||’%’)
order by table_name,column_name,endpoint_number
/
—
clear colu
spool off

 Comment 

show general stats for a table – more.sql

on June 23, 2008 at 1:22 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

–tab_all_stats
— mdw 30/11/04
— show the stats for a table, it’s coulns, it’s indexes…
set veri off pages 64 pause off lines 100
accept tabname prompt ‘Name for Table: ‘
col owner         form A8
col table_name    form A14 word wrap
col avg_sp        form 9,999
col avg_l         form 9999
col avg_sp        form 9,999
col n_buck        form 9,999
col chain         form 9,999
col clustf         form 999,999
col bl            form 999
col blocks        form 999,999
col low_v         form a10 trunc
col hi_v          form a10 trunc
col num_rows      form 99999,999
col dist_keys     form 99999,999
col l_blks        form 99999,999
col num_nulls     form 99,999
col column_name   form a20 word wrap
col index_name    form a15 word wrap
col buckno        form 99,999,999,999
col end_val       form 9,999,999,999,999
col end_act_val   form A10
col psn           form 99
spool tab_sci.lst
select owner
,table_name
,num_rows
,blocks
,avg_space   avg_sp
,chain_cnt   chain
,avg_row_len avg_l
,global_stats  gls
,user_stats    uls
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
,sample_size   samp_size
from dba_tables
where table_name = upper(nvl(‘&&tabname’,’eric’))
–where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
/
select index_name
,substr(index_type,1,3)   typ
,substr(uniqueness,1,3)   unq
,blevel                   bl
,leaf_blocks              l_blks
,distinct_keys            dist_keys
,clustering_factor        clustf
,avg_leaf_blocks_per_key  lb_key
,avg_data_blocks_per_key  db_key
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
from dba_indexes
where table_name = upper(nvl(‘&&tabname’,’eric’))
order by owner,index_name
/
 select
 INDEX_NAME                  index_Name
,TABLE_NAME                  table_Name
,substr(column_position,1,3) Psn
,COLUMN_NAME                 Column_Name
from all_ind_columns
where table_name = upper(nvl(‘&&tabname’,’WHOOPS’))
order by index_owner,1,2,3
/
—
select substr(owner,1,8) owner
–,table_name
,column_name
,num_distinct
,low_value    low_v
,high_value   hi_v
,num_nulls    n_nulls
,num_buckets  n_buck
,avg_col_len  avg_l
from dba_tab_columns
where table_name = upper(nvl(‘&&tabname’,’eric’))
–where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
order by owner,column_id
/
—
undefine
set pause on
clear colu
spool off

 

 Comment 

show stats for a partitioned table and its indexes

on June 23, 2008 at 1:22 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— show the stats for a partitioned table and it’s indexes… Courtesy of Martin Widlake

set veri off
pages 64
pause off
lines 100
feed off
timi off
accept tabname prompt ‘Name for Table: ‘
col owner         form A8
col table_name    form A14 word wrap
col tabpar_name    form A19 word wrap
col avg_sp        form 9,999
col avg_l         form 9,999
col avg_sp        form 9,999
col chain         form 999 head chn
col clustf        form 9999,999
col lbp_key       form 99,999
col dbp_key       form 99,999
col bl            form 999
col blocks        form 999,999
col num_rows      form 99999,999
col dist_keys     form 99999,999
col l_blks        form 99999,999
col column_name   form a15 word wrap
col index_name    form a15 word wrap
spool tab_par_stats.lst

SELECT owner, table_name, num_rows, blocks, avg_space   avg_sp, chain_cnt   chain, avg_row_len avg_l
  ,global_stats  gls, user_stats    uls, to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal, sample_size   samp_size

FROM dba_tables

WHERE table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)

ORDER BY table_name
/
— now partitions
SELECT –owner
  obj_maint.tab_alias(table_name)||’-‘||partition_name tabpar_name, num_rows, blocks, avg_space   avg_sp,
  chain_cnt   chain, avg_row_len avg_l, global_stats  gls, user_stats    uls,

  to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal, sample_size   samp_size
FROM dba_tab_partitions
WHERE table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
ORDER by table_name,partition_position
/
SELECT index_name, substr(index_type,1,3)   typ, substr(uniqueness,1,3)   unq, blevel  bl, leaf_blocks  l_blks,
  distinct_keys dist_keys, clustering_factor  clustf, avg_leaf_blocks_per_key  lbp_key, avg_data_blocks_per_key  dbp_key,
  to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
FROM dba_indexes
WHERE table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
ORDER by index_name
/
SELECTdip.partition_name index_name, dip.blevel  bl, dip.leaf_blocks l_blks, dip.distinct_keys dist_keys, 
   dip.clustering_factor        clustf, ,dip.avg_leaf_blocks_per_key  lbp_key, ,dip.avg_data_blocks_per_key  dbp_key,
   to_char(dip.last_analyzed,’DDMMYY hh24:MI:ss’) lst_anal
FROM dba_ind_partitions dip, dba_indexes dbin
WHERE dbin.table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
  AND dbin.index_name = dip.index_name
  AND dbin.owner=dip.index_owner
ORDER BY dbin.index_name, partition_position
/
set pause on timi on feed on
—
clear colu
spool off

 Comment 

show general stats for a partitioned table again.sql

on June 23, 2008 at 1:21 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

–tab_all_part_stats
— mdw 30/11/04
— show the stats for a table, it’s coulns, it’s indexes…
set veri off pages 64 pause off lines 100
accept tabname prompt ‘Name for Table: ‘
accept partname prompt ‘Name for partition: ‘
col owner         form A8
col table_name    form A14 word wrap
col tabpar_name   form A20 word wrap
col avg_sp        form 9,999
col avg_l         form 9999
col avg_sp        form 9,999
col n_buck        form 9,999
col chain         form 9,999
col clustf         form 9,999
col bl            form 999
col blocks        form 999,999
col low_v         form a10 trunc
col hi_v          form a10 trunc
col num_rows      form 99999,999
col dist_keys     form 99999,999
col l_blks        form 99999,999
col num_nulls     form 99,999
col column_name   form a20 word wrap
col index_name    form a15 word wrap
col rowcount      form 99,999,999,999
col end_val       form 9,999,999,999,999
col end_act_val   form A20
spool tab_all_part_stats.lst
select owner
,table_name
,num_rows
,blocks
,avg_space   avg_sp
,chain_cnt   chain
,avg_row_len avg_l
,global_stats  gls
,user_stats    uls
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
,sample_size   samp_size
from dba_tables
where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
/
select –owner
obj_maint.tab_alias(table_name)||’-‘||partition_name tabpar_name
,num_rows
,blocks
,avg_space   avg_sp
,chain_cnt   chain
,avg_row_len avg_l
,global_stats  gls
,user_stats    uls
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
,sample_size   samp_size
from dba_tab_partitions
where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
and partition_name like upper(nvl(‘&&partname’,’eric’)||’%’)
order by table_name,partition_position
/
select index_name
,substr(index_type,1,3)   typ
,substr(uniqueness,1,3)   unq
,blevel                   bl
,leaf_blocks              l_blks
,distinct_keys            dist_keys
,clustering_factor        clustf
,avg_leaf_blocks_per_key  lb_key
,avg_data_blocks_per_key  db_key
,to_char(last_analyzed,’DDMMYY hh24:MI’) lst_anal
from dba_indexes
where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
/
select dip.partition_name index_name
,dip.blevel                   bl
,dip.leaf_blocks              l_blks
,dip.distinct_keys            dist_keys
,dip.clustering_factor        clustf
,dip.avg_leaf_blocks_per_key  lbp_key
,dip.avg_data_blocks_per_key  dbp_key
,to_char(dip.last_analyzed,’DDMMYY hh24:MI:ss’) lst_anal
from dba_ind_partitions dip
,dba_indexes dbin
where dbin.table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
and dbin.index_name = dip.index_name
and dbin.owner=dip.index_owner
and dip.partition_name like upper(nvl(‘&&partname’,’eric’)||’%’)
order by dbin.index_name,partition_position
/
set pause on
—
select– owner
–,table_name
column_name
,num_distinct
,low_value    low_v
,high_value   hi_v
,num_nulls    n_nulls
,num_buckets  n_buck
,avg_col_len  avg_l
from dba_tab_columns
where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
order by column_name
/
col partition_name   form a12 word wrap
break on partition_name nodup
select– owner
–,table_name
partition_name
,substr(column_name,1,20) col_name
,num_distinct
,low_value    low_v
,high_value   hi_v
,num_nulls    n_nulls
,num_buckets  n_buck
,avg_col_len  avg_l
from dba_part_col_statistics
where table_name like upper(nvl(‘&&tabname’,’eric’)||’%’)
and partition_name like upper(nvl(‘&&partname’,’eric’)||’%’)
order by partition_name,column_name
/
—
select
column_name
,endpoint_value  end_val
,endpoint_number rowcount
,endpoint_actual_value  end_act_val
from all_tab_histograms
where table_name like upper(nvl(‘&tabname’,’WHOOPS’)||’%’)
order by table_name,column_name,endpoint_number
/
select
partition_name
,substr(column_name,1,20) col_name
,endpoint_value  end_val
,bucket_number rowcount
,endpoint_actual_value  end_act_val
from all_part_histograms
where table_name like upper(nvl(‘&tabname’,’WHOOPS’)||’%’)
and partition_name like upper(nvl(‘&&partname’,’eric’)||’%’)
order by table_name,partition_name,column_name,bucket_number
/
—
clear colu
spool off

 Comment 

show db sessions and sql text.sql

on June 23, 2008 at 1:21 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

SELECT /*+ ORDERED */
       s.sid, s.username, s.osuser,
       nvl(s.machine, ‘?’) machine,
       nvl(s.program, ‘?’) program,
       s.process F_Ground, p.spid B_Ground,
       X.sql_text
FROM   sys.v_$session S,
       sys.v_$process P,
       sys.v_$sqlarea X
WHERE  s.osuser      like lower(nvl(‘&OS_User’,’%’))
AND    s.username    like upper(nvl(‘&Oracle_User’,’%’))
AND    s.sid         like nvl(‘&SID’,’%’)
AND    s.paddr          = p.addr
AND    s.type          != ‘BACKGROUND’
AND    s.sql_address    = x.address
AND    s.sql_hash_value = x.hash_value
ORDER
    BY S.sid
/

 Comment 

sql to show current date and time

on June 23, 2008 at 1:21 pm
Posted In: Oracle odds and ends (Cat)

Courtesy of Martin Widlake

— SHOWTIME
— shows date and time, primarily to tell how much longer that days
— sentence of misery in the pit of dispair is to last. Bitter? You Bet.

col dt head ‘  Date       Time  ‘
set pause off
set feed off
SELECT SUBSTR(TO_CHAR(SYSDATE ,’DD-MON-YYYY HH24:MI:SS’), 1, 20) dt–“_DATE__________TIME_” FROM DUAL
/
clear colu
set pause on
set feed 6

 Comment 

sql to show archive and redo logs (Oracle 10g 11g)

on June 23, 2008 at 1:20 pm
Posted In: Oracle Flashback Notes (Cat)

—
col grp form 99
col sequ form 99999
col thrd form 999
col siz_k form 999,999
col file_name form a30 wrap
select log.group#         grp
,log.thread#              thrd
,log.sequence#            sequ
,log.bytes/1024           siz_k
,to_char(log.first_time,’DD-MM-HH:MI.SS’) first_tim
,substr(log.archived,1,1) ar
,substr(log.status,1,4)   sts
,logf.member              file_name
from v$log log
,v$logfile logf
where log.group#=logf.group#
order by log.group#,file_name
/
clear col

 Comment 

show archive and redo logs.sql

on June 23, 2008 at 1:20 pm
Posted In: Oracle Data Guard Notes (Cat)

—
col grp form 99
col sequ form 99999
col thrd form 999
col siz_k form 999,999
col file_name form a30 wrap
select log.group#         grp
,log.thread#              thrd
,log.sequence#            sequ
,log.bytes/1024           siz_k
,to_char(log.first_time,’DD-MM-HH:MI.SS’) first_tim
,substr(log.archived,1,1) ar
,substr(log.status,1,4)   sts
,logf.member              file_name
from v$log log
,v$logfile logf
where log.group#=logf.group#
order by log.group#,file_name
/
clear col

 Comment 

show all tables for a user.sql

on June 23, 2008 at 1:20 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

—
— tab_desc_usr.sql
— all tables for a user
— mdw date? way back in the mists of time
— my own replacement for desc.
— 16/11/01 improved the data_type section
 SET PAUSE ON
 –SET PAUSE ‘Any Key…>’
 set pause off
 SET PAGES 64
 col Tab_own form A10
 col tab_name form a22 wrap
 col col_name form a28 wrap
 col col_def form A14
 break on tab_own skip 1 on tab_name skip 1
 spool tab_desc_usr.lst
 select
— owner                               Tab_Own
 table_name             Tab_Name
,column_name            Col_Name
,decode(NULLABLE,’Y’,’N’,’Y’)        Mand
,data_type||decode(data_type
       ,’NUMBER’,'(‘
        ||decode(to_char(data_precision)
                ,null,’38’
                ,     to_char(data_precision)||
                      decode(data_scale,null,”
                                      ,      ‘,’||data_scale)
                 )
                    ||’)’
       ,’DATE’,null
       ,’LONG’,null
       ,’LONG RAW’,null
       ,'(‘||Substr(DATA_LENGTH,1,5)||’)’
         )  col_def
from dba_tab_columns
where owner like upper (nvl(‘&user_name’,’WHOOPS’)||’%’)
and table_name like upper (‘&TAB_NAME’||’%’)
order by 1,column_id,3,4
/
spool off
clear col
—

 Comment 

show all tables being accesed and the userid.sql

on June 23, 2008 at 1:20 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

REM reports which tables are in use by which users (on OPS)

set lines 120;
set pages 500;
set verify off;
set feed off;

column db_user format A20;
column program format A35;
column accessed_objects format A40;

break on db_user on program;

PROMPT ================================================================================================================
PROMPT Objects currently being accessed:
PROMPT ================================================================================================================

select
a.osuser||’@’||a.machine db_user,
a.program,
b.owner||’.’||b.object accessed_objects
from gv$session a, gv$access b
where
a.inst_id = b.inst_id and
a.sid = b.sid and
a.type = ‘USER’ and
b.owner != ‘PUBLIC’ and
b.type not in (‘SYNONYM’,’PACKAGE’)
order by a.osuser,a.machine,b.owner,b.object;

PROMPT ================================================================================================================

set feed on;

 

 Comment 

show active sql.sql

on June 23, 2008 at 1:19 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

REM script to look at the currently active SQL in the buffer and the user
REM and program responsible for it
REM
REM WARNING: This query is slow!
REM
REM

set linesize 100;
set pagesize 200;

column osuser format A10 trunc;
column osuser format A20 trunc;
column program format A30 trunc;

column disk_reads format 9,999,999,999;
column executions format 9,999,999,999;
column buffer_gets format 9,999,999,999;
column rows_processed format 9,999,999,999;

set time on;
set timing on;

select b.osuser,b.username,b.program,
c.disk_reads,c.executions,c.buffer_gets,c.rows_processed,
c.sql_text
from
v$session b, v$sqlarea c
where
b.sql_address = c.address and
b.username is not null and
b.status = ‘ACTIVE’ and
c.sql_text not like ‘%sqlarea%’
order by b.osuser,b.username;

 

 Comment 

show a users privileges.sql

on June 23, 2008 at 1:19 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— usr_privs.sql
— mdw 11/10/01
— select what privs a user has. Will need to be done in stages,
— selecting what sys privs a user has, what roles they have and what
— privs the role has. Hmmmm, this might be easier with PL/SQL
—
set pause on pages 32
spool usr_privs.lst
col grantee form a20 word wrap
col type    form a4 
col privilege form a40 word wrap
col admin_option form a3  head adm
accept usr_name char prompt ‘enter user whos privs you wish to see> ‘
select grantee, ‘SYSP’   type, privilege, admin_option from dba_sys_privs where grantee like nvl(upper(‘&usr_name’),’WHOOPS’)||’%’
union
select grantee, ‘ROLE’   type, granted_role    privelege, admin_option from dba_role_privs where grantee like nvl(upper(‘&usr_name’),’WHOOPS’)||’%’
union
select grantee, ‘OBJP’   type, owner||’.’||table_name||’-‘||privilege    privelege, grantable admin_option from dba_tab_privs where grantee like nvl(upper(‘&usr_name’),’WHOOPS’)||’%’
order by 1,2 desc,3
/
—
— MDW BELOW WILL NOT WORK BECAUSE ORACLE WON’T TREE WALK A VIEW WITH A
–     DISTINCT OR GROUP BY IN IT. ARSE
–select
–grantee
–,level   lvl
–,lpad(‘ ‘,2*level)||granted_role    privelege
–,admin_option
–from dba_role_privs
–connect by prior granted_role = grantee
–start with grantee like nvl(upper(‘&usr_name’),’WHOOPS’)||’%’
–order by 1
–/
—
— now an attempt to get all of the system privs granted via the roles
—
clear colu
spool off
— eof
—

 Comment 

set session trace on.sql

on June 23, 2008 at 1:18 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

alter session set sql_trace = true
/

 Comment 

set session trace off.sql

on June 23, 2008 at 1:18 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

alter session set sql_trace = false
/

 Comment 

sessions by pga usage.sql

on June 23, 2008 at 1:18 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

col mem_val form a28
     select value, sid, n.name|| ‘(‘||s.statistic#||’)’ mem_val
     from v$sesstat s , v$statname n
     where s.statistic# = n.statistic#
     and n.name like ‘session pga memory%’
     order by 1 desc
/

 Comment 

see what foreign keys are pointing to this table.sql

on June 23, 2008 at 1:17 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— chk_ref_by.sql
— see what fks are pointing to the PK and UNQs on a table (or set of tables)
— mdw 24/04/01
set pause on
set pages 24
col owner           form a8 word wrap
col table_name      form a15 word wrap
col cons            form a15 word wrap
col r_owner         form a8 word wrap
col r_cons          form a15 word wrap
col r_tab           form a10 word wrap
spool chk_ref_by.lst
select
dc.owner
,dc.table_name
,dc.constraint_name    cons
,dc.constraint_type    t
,dc2.owner             r_owner
,dc2.constraint_name   r_cons
,dc2.table_name        r_tab
from dba_constraints     dc
    ,dba_constraints     dc2
where dc2.r_owner           =   dc.owner
and   dc2.r_constraint_name =   dc.constraint_name
and   dc.constraint_type  in  (‘P’,’U’)
and dc.table_name like nvl(upper(‘&tab_name’),’WHOOPS’)||’%’
and dc.owner like nvl(upper(‘&tab_own’)||’%’,user)
order by dc.table_name,dc.owner
/
—
clear columns
spool off

 Comment 

query the plan_table.sql

on June 23, 2008 at 1:17 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

REM Queries the table PLAN_TABLE, retrieves and formats the execution plan
REM for the specified statement ID
REM
REM This works for SQL statements previously run using the following syntax:
REM
REM explain plan set statement_id = ‘whatever’ for ;
REM

set pages 500;
set lines 100;
set feed off;
set time on;
set timing on;
set arraysize 1;

column “Object” format A30;
column “Execution path” format A50;

accept stid prompt ‘Statement ID: ‘

select
object_name “Object”,lpad(‘ ‘,2*level)||Operation||’ ‘||Options “Execution path”
from plan_table
where
statement_id = ‘&stid’
connect by prior ID = parent_id and statement_id = ‘&stid’
start with ID=1;

delete from plan_table;
commit;

set feed on;

 Comment 

query all objects.sql

on June 23, 2008 at 1:16 pm
Posted In: Oracle DB Objects (tables, sql etc) (Cat)

— pkg_lst.sql
— mdw 02/02/00
— list of all packages and procedures stored on the
— database (that can be seen)
set pause on
set pages 24
set pause ‘Any Key>’
col name form a20 word wrap
col o_type form a15 word wrap
col owner form a20 word wrap
prompt ‘will ignore sys and system pl/sql’
spoo pkg_lst.lst
select
 object_name  Name
,object_type  O_Type
,owner        Owner
,status
from all_objects
where (object_type like ‘P%’
or object_type =’FUNCTION’)
and owner like upper(‘&OBJ_OWNER’||’%’)
and owner not in (‘SYS’,’SYSTEM’)
order by 1,2,3
/
spool off
clear colu

 Comment 

pgastat values.sql

on June 23, 2008 at 12:41 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

spool chk_pga.lst
set lines 85
col pga_name form a38 wrap
col name_val form 999,999,999,999
col val_k form 999,999,999
select name pga_name
,value  name_val
,unit   nam_unit
,value/1024  val_k
from v$pgastat
where name like ‘&pga_name’||’%’
/
spool off

 Comment 

pga_mem total max and freed.sql

on June 23, 2008 at 12:41 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

— chk_pga_mem.sql
select substr(name,1,40) param_name,value/1024 value_mb
from v$pgastat
where name in ( ‘total PGA allocated’,’maximum PGA allocated’
,’PGA memory freed back to OS’,’bytes processed’)
union
select substr(name,1,40) param_name,value value_mb
from v$pgastat
where name in ( ‘process count’)
/

 

 Comment 

loop and check pool usage.sql

on June 23, 2008 at 12:40 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

–ct1.sql
— check the various SGA and PGA/UGA areas
— VERSION FOR CONTINUOUS SPOOLING
—
set pause off feed off pages 90 timi off
col pga_mem form 9999,999,999
col uga_mem form 9999,999,999
col pga_stat_name form a38 wrap
col pga_stat_val form 999,999,999,999
–spool c1.lst
—
select to_char(sysdate,’DD-MON-YY HH24:MI:SS’) date_time
,count(*) sess from v$session
/
prompt sga
select name,block_size,(sum(buffers)*8)/1024 buffer_mb
from v$buffer_pool
group by name,block_size
/
prompt pga_mem
select sum( s.value) pga_mem
from v$statname n, v$sesstat s
where n.statistic# = s.statistic#
and n.name in (‘session pga memory’);
—
prompt uga_mem
select sum(s.value) uga_mem
from v$statname n, v$sesstat s
where n.statistic# = s.statistic#
and n.name in (‘session uga memory’);
—
prompt pga_stats
select name pga_stat_name,value,unit from
v$pgastat
/
—
prompt sqlworkareaactive
select * from
v$sql_workarea_active
where WORK_AREA_SIZE- EXPECTED_SIZE>54857600;
—
prompt v$process_sum
select sum(PGA_USED_MEM), sum(PGA_ALLOC_MEM) , sum(PGA_FREEABLE_MEM)
from v$process;
—
prompt
select PID,PGA_USED_MEM, PGA_ALLOC_MEM, PGA_FREEABLE_MEM from
v$process order by PGA_ALLOC_MEM;
—
prompt v$processmemdetail
select * from v$process_memory_detail;
—
–spool off
— eof

 Comment 

look for sql in the sga containing the provided text.sql

on June 23, 2008 at 12:40 pm
Posted In: Oracle DB and SQL performance analysis (Cat)

— chk_sga_txt.sql
— mdw – look for sql in sga containing the provided txt
—
set pause on
set pages 36
spool chk_sga_txt
select
first_load_time
,parse_calls prse
,executions  excs
,buffer_gets buffs
,disk_reads   discs
,rows_processed rws
–,address        address
,hash_value     hash_value
,sql_text
from v$sqlarea
–where parsing_schema_id !=’0′
where sql_text like ‘%’||nvl(‘&sql_txt’,’whoops’)||’%’
–order by first_load_time desc
order by (greatest(buffer_gets,1)/greatest(rows_processed,1)) desc
/
spool off

 Comment 
  • Page 4 of 5
  • «
  • 1
  • 2
  • 3
  • 4
  • 5
  • »

©2006-2017 isitdevops.com/databases | Powered by WordPress with ComicPress | Subscribe: RSS | Back to Top ↑