Oracle DBA – Tips and Techniques

Knowledge is Power – so share it ….

Archive for the ‘Scripts’ Category

DBUPGDIAG script to check integrity of database before 11g upgrade

Posted by Arjun Raja on August 20, 2009

Script to check integrity of a 9i or 10g database before upgrade to 11g.

Run this script connected as sysdba in the 9i or 10g database.

NAME: DBUPGDIAG.SQL

This script can be downloaded from Oracle Metalink note 556610.1

– PURPOSE:
– This script is intended to provide a user friendly output to diagonise
– the status of the database before (or) after upgrade. The script will
– create a file called db_upg_diag__.log in your local
– working directory. This does not make any DDL / DML modifications.

– This script will work in both Windows and Unix platforms from database
– version 9.2 or higher.

col TODAY NEW_VALUE _DATE
col VERSION NEW_VALUE _VERSION
set termout off
select to_char(SYSDATE,’fmMonth DD, YYYY’) TODAY from DUAL;
select version from v$instance;
set termout on
set echo off
set feedback off
set head off
set verify off
Prompt
PROMPT Enter location for Spooled output:
Prompt
DEFINE log_path = &1
column timecol new_value timestamp
column spool_extension new_value suffix
SELECT to_char(sysdate,’dd-Mon-yyyy_hhmi’) timecol,’.log’ spool_extension FROM
sys.dual;
column output new_value dbname
SELECT value || ‘_’ output FROM v$parameter WHERE name = ‘db_name’;
spool &log_path/db_upg_diag_&&dbname&&timestamp&&suffix
set linesize 150
set pages 100
set trim on
set trims on
col Compatible for a35
col comp_id for a12
col comp_name for a40
col org_version for a11
col prv_version for a11
col owner for a12
col object_name for a40
col object_type for a40
col Wordsize for a25
col Metadata for a8
col ‘Initial DB Creation Info’ for a35
col ‘Total Invalid JAVA objects’ for a45
col ‘Role’ for a30
col ‘User Existence’ for a27
col “JAVAVM TESTING” for a15
Prompt
Prompt
set feedback off head off
select LPAD(‘*** Start of LogFile ***’,50) from dual;
select LPAD(‘Oracle Database Upgrade Diagnostic Utility’,44)||
LPAD(TO_CHAR(SYSDATE, ‘MM-DD-YYYY HH24:MI:SS’),26) from dual;
Prompt
Prompt ===============
Prompt Database Uptime
Prompt ===============
SELECT to_char(startup_time, ‘HH24:MI DD-MON-YY’) “Startup Time”
FROM v$instance;
Prompt
Prompt =================
Prompt Database Wordsize
Prompt =================
SELECT distinct(‘This is a ‘ || (length(addr)*4) || ‘-bit database’) “WordSize”
FROM v$process;
Prompt
Prompt ================
Prompt Software Verison
Prompt ================
SELECT * FROM v$version;
Prompt
Prompt =============
Prompt Compatibility
Prompt =============
SELECT ‘Compatibility is set as ‘||value Compatible
FROM v$parameter WHERE name =’compatible’;
Prompt
Prompt ================
Prompt Component Status
Prompt ================
Prompt
SET SERVEROUTPUT ON;
DECLARE

ORG_VERSION varchar2(12);
PRV_VERSION varchar2(12);
P_VERSION VARCHAR2(10);

BEGIN

SELECT version INTO p_version
FROM registry$ WHERE cid=’CATPROC’ ;

IF SUBSTR(p_version,1,5) = ‘9.2.0′ THEN

DBMS_OUTPUT.PUT_LINE(RPAD(‘Comp ID’, 8) ||RPAD(‘Component’,35)||
RPAD(‘Status’,10) ||RPAD(‘Version’, 15));

DBMS_OUTPUT.PUT_LINE(RPAD(‘ ‘,8,’-') ||RPAD(‘ ‘,35,’-')||
RPAD(‘ ‘,10,’-') ||RPAD(‘ ‘,15,’-'));

FOR x in (SELECT SUBSTR(dr.comp_id,1,8) comp_id,
SUBSTR(dr.comp_name,1,35) comp_name,
dr.status Status,SUBSTR(dr.version,1,15) version
FROM dba_registry dr,registry$ r
WHERE dr.comp_id=r.cid and dr.comp_name=r.cname
ORDER BY 1)

LOOP

DBMS_OUTPUT.PUT_LINE(RPAD(SUBSTR(x.comp_id,1,8),8) ||
RPAD(SUBSTR(x.comp_name,1,35),35)||
RPAD(x.status,10) || RPAD(x.version, 15));
END LOOP;

ELSIF SUBSTR(p_version,1,5) != ‘9.2.0′ THEN

DBMS_OUTPUT.PUT_LINE(RPAD(‘Comp ID’, 8) ||RPAD(‘Component’,35)||
RPAD(‘Status’,10) ||RPAD(‘Version’, 15)||
RPAD(‘Org_Version’,15)||RPAD(‘Prv_Version’,15));

DBMS_OUTPUT.PUT_LINE(RPAD(‘ ‘,8,’-') ||RPAD(‘ ‘,35,’-')||
RPAD(‘ ‘,10,’-')||RPAD(‘ ‘,15,’-')||RPAD(‘ ‘,15,’-')||
RPAD(‘ ‘,15,’-'));

FOR y in (SELECT SUBSTR(dr.comp_id,1,8) comp_id,
SUBSTR(dr.comp_name,1,35) comp_name, dr.status Status,
SUBSTR(dr.version,1,11) version,org_version,prv_version
FROM dba_registry dr,registry$ r
WHERE dr.comp_id=r.cid and dr.comp_name=r.cname
ORDER BY 1)

LOOP

DBMS_OUTPUT.PUT_LINE(RPAD(substr(y.comp_id,1,8), 8) ||
RPAD(substr(y.comp_name,1,35),35)||RPAD(y.status,10) ||
RPAD(y.version, 15)||RPAD(y.org_version,15)||RPAD(y.prv_version,15));

END LOOP;

END IF;
END;
/
SET SERVEROUTPUT OFF
Prompt
Prompt
Prompt ======================================================
Prompt List of Invalid Database Objects Owned by SYS / SYSTEM
Prompt ======================================================
Prompt
set head on
SELECT case count(object_name)
WHEN 0 THEN ‘There are no Invalid Objects’
ELSE ‘There are ‘||count(object_name)||’ Invalid objects’
END “Number of Invalid Objects”
FROM dba_objects
WHERE status=’INVALID’
AND owner in (‘SYS’,'SYSTEM’);
Prompt
DOC
################################################################

If there are no Invalid objects below will result in zero rows.

################################################################
#
Prompt
set feedback on
SELECT owner,object_name,object_type
FROM dba_objects
WHERE status=’INVALID’
AND owner in (‘SYS’,'SYSTEM’)
ORDER BY owner,object_type;
set feedback off
Prompt
Prompt ================================
Prompt List of Invalid Database Objects
Prompt ================================
Prompt
set head on
SELECT case count(object_name)
WHEN 0 THEN ‘There are no Invalid Objects’
ELSE ‘There are ‘||count(object_name)||’ Invalid objects’
END “Number of Invalid Objects”
FROM dba_objects
WHERE status=’INVALID’
AND owner not in (‘SYS’,'SYSTEM’);
Prompt
DOC
################################################################

If there are no Invalid objects below will result in zero rows.

################################################################
#
Prompt
set feedback on
SELECT owner,object_name,object_type
FROM dba_objects
WHERE status=’INVALID’
AND owner not in (‘SYS’,'SYSTEM’)
ORDER BY owner,object_type;
set feedback off
Prompt
Prompt ==============================================================
Prompt Identifying whether a database was created as 32-bit or 64-bit
Prompt ==============================================================
Prompt
DOC
###########################################################################

Result referencing the string ‘B023′ ==> Database was created as 32-bit
Result referencing the string ‘B047′ ==> Database was created as 64-bit
When String results in ‘B023′ and when upgrading database to 10.2.0.3.0
(64-bit) , For known issue refer below articles

Note 412271.1 ORA-600 [22635] and ORA-600 [KOKEIIX1] Reported While
Upgrading Or Patching Databases To 10.2.0.3
Note 579523.1 ORA-600 [22635], ORA-600 [KOKEIIX1], ORA-7445 [KOPESIZ] and
OCI-21500 [KOXSIHREAD1] Reported While Upgrading To 11.1.0.6

###########################################################################
#
Prompt
SELECT SUBSTR(metadata,109,4) “Metadata”,
CASE SUBSTR(metadata,109,4)
WHEN ‘B023′ THEN ‘Database was created as 32-bit’
WHEN ‘B047′ THEN ‘Database was created as 64-bit’
ELSE ‘Metadata not Matching’
END “Initial DB Creation Info”
FROM sys.kopm$;
Prompt
Prompt ===================================================
Prompt Number of Duplicate Objects Owned by SYS and SYSTEM
Prompt ===================================================
Prompt
Prompt Counting duplicate objects ….
Prompt
SELECT count(1)
FROM dba_objects
WHERE object_name||object_type in
(SELECT object_name||object_type
from dba_objects
where owner = ‘SYS’)
and owner = ‘SYSTEM’;
Prompt
Prompt =========================================
Prompt Duplicate Objects Owned by SYS and SYSTEM
Prompt =========================================
Prompt
Prompt Querying duplicate objects ….
Prompt
SELECT object_name, object_type
FROM dba_objects
WHERE object_name||object_type in
(SELECT object_name||object_type
FROM dba_objects
WHERE owner = ‘SYS’)
AND owner = ‘SYSTEM’;
Prompt
DOC

################################################################################

If any objects found please follow below article.
Note 1030426.6 How to Clean Up Duplicate Objects Owned by SYS and SYSTEM schema
Read the Exceptions carefully before taking actions.

################################################################################
#
Prompt
Prompt ================
Prompt JVM Verification
Prompt ================
Prompt
SET SERVEROUTPUT ON
DECLARE

V_CT NUMBER;
P_VERSION VARCHAR2(10);

BEGIN

– If so, get the version of the JAVAM component
EXECUTE IMMEDIATE ‘SELECT version FROM registry$ WHERE cid=”JAVAVM”
AND status 99′ INTO p_version;

SELECT count(*) INTO v_ct FROM dba_objects
WHERE object_type LIKE ‘%JAVA%’ AND owner=’SYS’;

IF SUBSTR(p_version,1,5) = ‘8.1.7′ THEN
IF v_ct>=6787 THEN
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Installed properly’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Not Installed properly’);
END IF;
ELSIF SUBSTR(p_version,1,5) = ‘9.0.1′ THEN
IF v_ct>=8585 THEN
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Installed properly’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Not Installed properly’);
END IF;
ELSIF SUBSTR(p_version,1,5) = ‘9.2.0′ THEN
IF v_ct>=8585 THEN
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Installed properly’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Not Installed properly’);
END IF;
ELSIF SUBSTR(p_version,1,6) = ‘10.1.0′ THEN
IF v_ct>=13866 THEN
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Installed properly’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Not Installed properly’);
END IF;
ELSIF SUBSTR(p_version,1,6) = ‘10.2.0′ THEN
IF v_ct>=14113 THEN
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Installed properly’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – Not Installed properly’);
END IF;
END IF;

EXCEPTION WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(‘JAVAVM – NOT Installed. Below results can be ignored’);

END;
/
SET SERVEROUTPUT OFF
Prompt
Prompt ================================================
Prompt Checking Existence of Java-Based Users and Roles
Prompt ================================================
Prompt
DOC

################################################################################

There should not be any Java Based users for database version 9.0.1 and above.
If any users found, it is faulty JVM.

################################################################################
#

Prompt
SELECT CASE count(username)
WHEN 0 THEN ‘No Java Based Users’
ELSE ‘There are ‘||count(*)||’ JAVA based users’
END “User Existence”
FROM dba_users WHERE username LIKE ‘%AURORA%’ AND username LIKE ‘%OSE%’;
Prompt
DOC

###############################################################

Healthy JVM Should contain Six Roles.
If there are more or less than six role, JVM is inconsistent.

###############################################################
#

Prompt
SELECT CASE count(role)
WHEN 0 THEN ‘No JAVA related Roles’
ELSE ‘There are ‘||count(role)||’ JAVA related roles’
END “Role”
FROM dba_roles
WHERE role LIKE ‘%JAVA%’;
Prompt
Prompt Roles
Prompt
SELECT role FROM dba_roles WHERE role LIKE ‘%JAVA%’;
set head off
Prompt
Prompt =========================================
Prompt List of Invalid Java Objects owned by SYS
Prompt =========================================
SELECT CASE count(*)
WHEN 0 THEN ‘There are no SYS owned invalid JAVA objects’
ELSE ‘There are ‘||count(*)||’ SYS owned invalid JAVA objects’
END “Total Invalid JAVA objects”
FROM dba_objects
WHERE object_type LIKE ‘%JAVA%’
AND status=’INVALID’
AND owner=’SYS’;
Prompt
DOC

#################################################################

Check the status of the main JVM interface packages DBMS_JAVA
and INITJVMAUX and make sure it is VALID.
If there are no Invalid objects below will result in zero rows.

#################################################################
#
Prompt
set feedback on
SELECT owner,object_name,object_type
FROM dba_objects
WHERE object_type LIKE ‘%JAVA%’
AND status=’INVALID’
AND owner=’SYS’;
set feedback off
Prompt
Prompt INFO: Below query should succeed with ‘foo’ as result.
set heading on
select dbms_java.longname(‘foo’) “JAVAVM TESTING” from dual;
set heading off
Prompt

set feedback off head off
select LPAD(‘*** End of LogFile ***’,50) from dual;
set feedback on head on
Prompt
spool off
Prompt
set heading off
set heading off
set feedback off
select ‘Upload db_upg_diag_&&dbname&&timestamp&&suffix from “&log_path” directory’
from dual;
set heading on
set feedback on
Prompt
– – - – - – - – - – - – - – - – Script ends here – - – - – - – - – - – - – -

Posted in Scripts | Tagged: , | Leave a Comment »

Script – Check RMAN Backup Status

Posted by Arjun Raja on July 28, 2009

Scripts to check backup status and timings of database backups -

This script will be run in the database, not the catalog.

Login as sysdba -

This script will report on all backups – full, incremental and archivelog backups -

col STATUS format a9
col hrs format 999.99
select
SESSION_KEY, INPUT_TYPE, STATUS,
to_char(START_TIME,'mm/dd/yy hh24:mi') start_time,
to_char(END_TIME,'mm/dd/yy hh24:mi')   end_time,
elapsed_seconds/3600                   hrs
from V$RMAN_BACKUP_JOB_DETAILS
order by session_key;

This script will report all on full and incremental backups, not archivelog backups -

col STATUS format a9
col hrs format 999.99
select
SESSION_KEY, INPUT_TYPE, STATUS,
to_char(START_TIME,'mm/dd/yy hh24:mi') start_time,
to_char(END_TIME,'mm/dd/yy hh24:mi')   end_time,
elapsed_seconds/3600                   hrs
from V$RMAN_BACKUP_JOB_DETAILS
where input_type='DB INCR'
order by session_key;

Posted in Administration, Backup and Recovery, Scripts | Tagged: , , | Leave a Comment »

Script – Sessions with high physical reads

Posted by Gavin Soorma on July 9, 2009

 set linesize 120
col os_user format a10
col username format a15

col pid format 9999999999
PROMPT SESSIONS SORTED BY PHYSICAL READS
PROMPT
select
  OSUSER os_user,username,
    PROCESS pid,
    ses.SID sid,
    SERIAL#,
    PHYSICAL_READS,
     BLOCK_CHANGES
 from       v$session ses,
   v$sess_io sio
  where      ses.SID = sio.SID
and username is not null
and status='ACTIVE'
 order      by PHYSICAL_READS;

Posted in Performance Tuning, Scripts | Tagged: , , , , | Leave a Comment »

Script – Monitor Flashback Logs

Posted by Gavin Soorma on July 9, 2009

PROMPT How Far Back Can We Flashback To (Time)?
PROMPT
select to_char(oldest_flashback_time,'dd-mon-yyyy hh24:mi:ss') "Oldest Flashback Time"
 from v$flashback_database_log;

PROMPT
PROMPT How Far Back Can We Flashback To (SCN)?
PROMPT
col oldest_flashback_scn format 99999999999999999999999999
select oldest_flashback_scn from v$flashback_database_log;

PROMPT
PROMPT Flashback Area Usage
SELECT * FROM   V$FLASH_RECOVERY_AREA_USAGE;

PROMPT
col ROUND(SPACE_LIMIT/1048576) heading "Space Allocated (MB)" format 999999
col round(space_used/1048576) heading "Space Used (MB)" format 99999
col name Heading "Flashback Location" format a40

select name, round(space_limit/1048576),round(space_used/1048576)
 from  v$RECOVERY_FILE_DEST;

How Far Back Can We Flashback To (Time)?

Oldest Flashback Time
-----------------------------
05-jul-2009 22:53:07

How Far Back Can We Flashback To (SCN)?

       OLDEST_FLASHBACK_SCN
---------------------------
                15321928761

Flashback Area Usage

FILE_TYPE    PERCENT_SPACE_USED PERCENT_SPACE_RECLAIMABLE NUMBER_OF_FILES
------------ ------------------ ------------------------- ---------------
CONTROLFILE                   0                         0               0
ONLINELOG                     0                         0               0
ARCHIVELOG                16.33                     16.33              51
BACKUPPIECE               16.34                     16.34               6
IMAGECOPY                     0                         0               0
FLASHBACKLOG              45.94                     10.61             204

6 rows selected.

Flashback Location                       Space Allocated (MB) Space Used (MB)
---------------------------------------- -------------------- ---------------
/u05/oradata/flash_recovery_area                         5120            4025

Posted in Monitoring | Tagged: , , , , , , | Leave a Comment »

Script – Database structure and file location

Posted by Gavin Soorma on July 7, 2009

set pagesize 500
set linesize 130
Prompt
Prompt Control Files Location >>>>
col name  format a60 heading "Control Files"

select name
from   sys.v_$controlfile
/

Prompt
Prompt Redo Log File Locations >>>>
Prompt

col Grp    format 9999
col member format a50 heading "Online REDO Logs"
col File#  format 9999
col name   format a50 heading "Online REDO Logs"
break on Grp
select group#,member
from   sys.v_$logfile
/

Prompt Data Files Locations >>>>

col Tspace    format a25
col status    format a3  heading Sta
col Id        format 9999
col Mbyte     format 999999999
col name      format a50 heading "Database Data Files"
col Reads     format 99,999,999
col Writes    format 99,999,999

break on report
compute sum label 'Total(MB)'  of Mbyte  on report 

select F.file_id Id,
       F.file_name name,
       F.bytes/(1024*1024) Mbyte,
       decode(F.status,'AVAILABLE','OK',F.status) status,
       F.tablespace_name Tspace
from   sys.dba_data_files F
order by tablespace_name;

Control Files Location >>>>

Control Files
------------------------------------------------------------
/u03/oradata/rcatp/control01.ctl
/u05/oradata/rcatp/control02.ctl

Redo Log File Locations >>>>

    GROUP# Online REDO Logs
---------- --------------------------------------------------
         1 /u03/oradata/rcatp/redo01.log
         2 /u05/oradata/rcatp/redo02.log
         3 /u03/oradata/rcatp/redo03.log
         3 /u05/oradata/rcatp/redo03b.log
         1 /u05/oradata/rcatp/redo01b.log
         2 /u03/oradata/rcatp/redo02b.log

6 rows selected.

Data Files Locations >>>>

   ID Database Data Files                                     MBYTE Sta TSPACE
----- -------------------------------------------------- ---------- --- -------------------------
    9 /u03/oradata/rcatp/patrol01.dbf                            20 OK  PATROL
    7 /u03/oradata/rcatp/rman10p01.dbf                          466 OK  RMAN10P
    5 /u03/oradata/rcatp/rman11p01.dbf                          200 OK  RMAN11P
    8 /u03/oradata/rcatp/rman9p01.dbf                           106 OK  RMAN9P
    3 /u03/oradata/rcatp/sysaux01.dbf                           540 OK  SYSAUX
    1 /u03/oradata/rcatp/system01.dbf                           700 OK  SYSTEM
    2 /u03/oradata/rcatp/undotbs01.dbf                          220 OK  UNDOTBS1
    4 /u03/oradata/rcatp/users01.dbf                              6 OK  USERS
                                                         ----------
sum                                                            2258

8 rows selected.

Posted in Scripts | Tagged: , , , , | Leave a Comment »

Script – Tablespace free space and fragmentation

Posted by Gavin Soorma on July 7, 2009


      set linesize 150
        column tablespace_name format a20 heading 'Tablespace'
     column sumb format 999,999,999
     column extents format 9999
     column bytes format 999,999,999,999
     column largest format 999,999,999,999
     column Tot_Size format 999,999 Heading 'Total| Size(Mb)'
     column Tot_Free format 999,999,999 heading 'Total Free(MB)'
     column Pct_Free format 999.99 heading '% Free'
     column Chunks_Free format 9999 heading 'No Of Ext.'
     column Max_Free format 999,999,999 heading 'Max Free(Kb)'
     set echo off
     PROMPT  FREE SPACE AVAILABLE IN TABLESPACES
     select a.tablespace_name,sum(a.tots/1048576) Tot_Size,
     sum(a.sumb/1048576) Tot_Free,
     sum(a.sumb)*100/sum(a.tots) Pct_Free,
     sum(a.largest/1024) Max_Free,sum(a.chunks) Chunks_Free
     from
     (
     select tablespace_name,0 tots,sum(bytes) sumb,
     max(bytes) largest,count(*) chunks
     from dba_free_space a
     group by tablespace_name
     union
     select tablespace_name,sum(bytes) tots,0,0,0 from
      dba_data_files
     group by tablespace_name) a
     group by a.tablespace_name
order by pct_free;

                         Total
Tablespace            Size(Mb) Total Free(MB)  % Free Max Free(Kb) No Of Ext.
-------------------- --------- -------------- ------- ------------ ----------
SYSTEM                     790              3     .38        3,008          2
SYSAUX                     752             52    6.86       32,768        132
USERS                        5              1   11.25          576          1
MGMT_ECM_DEPOT_TS          100             43   43.25       43,968          2
MGMT_TABLESPACE         13,940          8,388   60.17      155,200       1594
UNDOTBS1                   605            491   81.07      311,360         44
PATROL                       1              1   93.75          960          1

Posted in Scripts | Tagged: , , , , | Leave a Comment »

Data Guard Switchover Unix shell script

Posted by Gavin Soorma on July 6, 2009

The following Unix shell scripts can be used to automate the Data Guard Switchover process of a physical standby database.

It is very important that the scripts are run in the correct order and on right machine.

These scripts are based on a few customisations. The *.sh scripts are located in a directory called “/var/opt/oracle/dataguard” and there is another file called “set$ORACLE_SID” which is located under “/var/opt/oracle/cronjobs”. This script sets the environment for the individual Oracle instance like the $ORACLE_SID and the $ORACLE_HOME.

On the machine where the Primary Database is running we need to run the following scripts

$ cd /var/opt/oracle/dataguard
$ ./pre_switchover_check.sh
$ ./make_me_standby.sh

On the machine where the Standby Database is running we need to run the following script:

$ cd /var/opt/oracle/dataguard
$ ./make_me_primary.sh

After the switchover is completed, we need to run the following script on the machine where the former Primary (now new Standby) database is running:

$ cd /var/opt/oracle/dataguard
$ ./start_recovery.sh

pre_switchover_check.sh

!/bin/ksh

if [ "$1" = "" ]
then
echo ""
echo "##################################################################"
echo "# PLEASE ENTER ORACLE_SID AS THE FIRST COMMAND LINE ARGUMENT     #"
echo "#      SCRIPT USAGE : pre_switchover_check.sh        #"
echo "##################################################################"
echo ""
exit
fi

ORACLE_SID=`echo $1 |tr '[A-Z]' '[a-z]'`; export ORACLE_SID;

ls -l /var/opt/oracle/cronjobs/set$ORACLE_SID > /dev/null
if [ $? != 0 ]
then
echo ""
echo "##################################################################"
echo "#           ENVIRONMENT SETTING SET FILE NOT FOUND...!!!         #"
echo "#           /var/opt/oracle/cronjobs/set$ORACLE_SID              #"
echo "##################################################################"
echo ""
exit
fi

. /var/opt/oracle/cronjobs/set$ORACLE_SID

DB=`echo $1 |tr '[a-z]' '[A-Z]'`; export DB;

echo ""
echo "##################################################################"
echo "#            PERFORMING PRE-SWITCHOVER CHECKS FOR $DB            #"
echo "##################################################################"
echo ""

sqlplus  -s /nolog |&
print -p  "connect / as sysdba"
print -p  "set feedback off pause off pagesize 0 heading off verify off linesize 500 term off "
print -p  "set sqlprompt ''"
read  -p   JUNK
print -p  "SELECT DATABASE_ROLE DBROLE FROM V\$DATABASE;"
read  -p   DBROLE
print -p  "SELECT COUNT(FILE#) FILESTAT FROM V\$DATAFILE WHERE STATUS IN ('RECOVER', 'OFFLINE');"
read  -p   FILESTAT
print -p  "SELECT COUNT(FILE#) BKPSTAT FROM V\$BACKUP WHERE STATUS = 'ACTIVE';"
read  -p   BKPSTAT
print -p  "SELECT LOG_ARCHIVED-LOG_APPLIED LOGGAP
FROM (SELECT MAX(SEQUENCE#) LOG_ARCHIVED
FROM V\$ARCHIVED_LOG WHERE DEST_ID=1 AND ARCHIVED='YES'
AND RESETLOGS_CHANGE#=(SELECT MAX(RESETLOGS_CHANGE#)
FROM V\$ARCHIVED_LOG)),
(SELECT MAX(SEQUENCE#) LOG_APPLIED
FROM V\$ARCHIVED_LOG WHERE DEST_ID=2
AND APPLIED='YES'
AND RESETLOGS_CHANGE#=(SELECT MAX(RESETLOGS_CHANGE#) FROM V\$ARCHIVED_LOG)) ;"
read  -p   LOGGAP
print -p  "EXIT"

echo "CHECKING CURRENT DATABASE ROLE..."
if [ "$DBROLE" = "PHYSICAL STANDBY"  ]
then
echo ""
echo "##################################################################"
echo "# ERROR ! ! ! NOT  A PRIMARY DATABASE, PLEASE RUN IT ON PRIMARY  #"
echo "##################################################################"
echo ""
exit
else
echo ""
echo "   OK   "
echo ""
fi

echo "CHECKING LOG GAP BETWEEN PRIMARY & STANDBY..."
if [ $LOGGAP -ne 0 ]
then
echo ""
echo "######################################################################"
echo "# ERROR ! ! !  PRIMARY & STANDBY ARE NOT IN SYNC, LOG GAP = $LOGGAP  #"
echo "######################################################################"
echo ""
exit
else
echo ""
echo "   OK   "
echo ""
fi

echo "CHECKING FILES OFFLINE OR RECOVER STATUS..."
if [ $FILESTAT -ne 0 ]
then
echo ""
echo "##################################################################"
echo "#  ERROR ! ! !  ONE OR MORE FILE/S OFFLINE OR IN RECOVER STATUS  #"
echo "##################################################################"
echo ""
exit
else
echo ""
echo "   OK   "
echo ""
fi

echo "CHECKING FILES IN BACKUP MODE..."
if [ $BKPSTAT -ne 0 ]
then
echo ""
echo "##################################################################"
echo "#      ERROR ! ! !  ONE OR MORE FILE/S ARE IN BACKUP MODE        #"
echo "##################################################################"
echo ""
exit
else
echo ""
echo "   OK   "
echo ""
fi

echo ""
echo "##################################################################"
echo "# ALL PRE-SWITCHOVER CHECKS SUCCEEDED... PROCEED WITH SWITCHOVER #"
echo "##################################################################"
echo ""
make_me_standby.sh

#!/bin/ksh

if [ "$1" = "" ]
then
echo ""
echo "##################################################################"
echo "# PLEASE ENTER ORACLE_SID AS THE FIRST COMMAND LINE ARGUMENT     #"
echo "#        SCRIPT USAGE : make_me_standby.sh           #"
echo "##################################################################"
echo ""
exit
fi

ORACLE_SID=`echo $1 |tr '[A-Z]' '[a-z]'`; export ORACLE_SID;

ls -l /var/opt/oracle/cronjobs/set$ORACLE_SID > /dev/null
if [ $? != 0 ]
then
echo ""
echo "##################################################################"
echo "#           ENVIRONMENT SETTING SET FILE NOT FOUND...!!!         #"
echo "#           /var/opt/oracle/cronjobs/set$ORACLE_SID              #"
echo "##################################################################"
echo ""
exit
fi

. /var/opt/oracle/cronjobs/set$ORACLE_SID

DB=`echo $1 |tr '[a-z]' '[A-Z]'`; export DB;

sqlplus  -s /nolog |&
print -p  "connect / as sysdba"
print -p  "set feedback off pause off pagesize 0 heading off verify off linesize 500 term off"
print -p  "set sqlprompt ''"
read  -p   JUNK
print -p  "SELECT DATABASE_ROLE DBROLE FROM V\$DATABASE;"
read  -p   DBROLE
print -p  "SELECT COUNT(FILE#) FILESTAT FROM V\$DATAFILE WHERE STATUS IN ('RECOVER', 'OFFLINE');"
read  -p   FILESTAT
print -p  "SELECT COUNT(FILE#) BKPSTAT FROM V\$BACKUP WHERE STATUS = 'ACTIVE';"
read  -p   BKPSTAT
print -p  "SELECT LOG_ARCHIVED-LOG_APPLIED LOGGAP
FROM (SELECT MAX(SEQUENCE#) LOG_ARCHIVED
FROM V\$ARCHIVED_LOG WHERE DEST_ID=1 AND ARCHIVED='YES'
AND RESETLOGS_CHANGE#=(SELECT MAX(RESETLOGS_CHANGE#)
FROM V\$ARCHIVED_LOG)),
(SELECT MAX(SEQUENCE#) LOG_APPLIED
FROM V\$ARCHIVED_LOG WHERE DEST_ID=2
AND APPLIED='YES'
AND RESETLOGS_CHANGE#=(SELECT MAX(RESETLOGS_CHANGE#) FROM V\$ARCHIVED_LOG)) ;"
read  -p   LOGGAP
print -p  "EXIT"

if [ "$DBROLE" = "PHYSICAL STANDBY"  ]
then
echo ""
echo "##################################################################"
echo "# ERROR ! ! ! NOT  A PRIMARY DATABASE, PLEASE RUN IT ON PRIMARY  #"
echo "##################################################################"
echo ""
exit
fi

if [ $LOGGAP -ne 0 ]
then
echo ""
echo "######################################################################"
echo "# ERROR ! ! !  PRIMARY & STANDBY ARE NOT IN SYNC, LOG GAP = $LOGGAP  #"
echo "######################################################################"
echo ""
exit
fi

echo "CHECKING FILES OFFLINE OR RECOVER STATUS..."
if [ $FILESTAT -ne 0 ]
then
echo ""
echo "##################################################################"
echo "#  ERROR ! ! !  ONE OR MORE FILE/S OFFLINE OR IN RECOVER STATUS  #"
echo "##################################################################"
echo ""
exit
fi

if [ $BKPSTAT -ne 0 ]
then
echo ""
echo "##################################################################"
echo "#      ERROR ! ! !  ONE OR MORE FILE/S ARE IN BACKUP MODE        #"
echo "##################################################################"
echo ""
exit
fi

echo ""
echo "##################################################################"
echo "#              ALL PRE-SWITCHOVER CHECKS SUCCEEDED...            #"
echo "       SWITCHING $DB TO STANDBY ROLE, PLEASE CONFIRM ...          "
echo "##################################################################"
echo ""
echo ""
echo "Continue? - Please enter 'Y' to proceed & 'N' to exit"
read ans
if [ "$ans" = 'Y' -o "$ans" = 'y' ]
then
sqlplus -s  /nolog < /tmp/make_me_standby.log
connect / as sysdba;
startup force;
alter database commit to switchover to standby with session shutdown;
shutdown immediate;
startup nomount;
alter database mount standby database;
select database_role from v\$database;
EOF
cat /tmp/make_me_standby.log
$ORACLE_HOME/bin/lsnrctl stop PRIMARY_$DB
else
echo "Quitting ....."
exit
fi

echo ""
echo "####################################################################"
echo "# PLEASE CONFIRM THAT THE STATUS OF DATABASE IS NOW "STANDBY"      #"
echo "#                                                                  #"
echo "# On OLD STANDBY Host please run the following script:         #"
echo "# /var/opt/oracle/dataguard/make_me_primary.sh                #"
echo "####################################################################"
echo ""
make_me_primary.sh

#!/bin/ksh

if [ "$1" = "" ]
then
echo ""
echo "##################################################################"
echo "#  PLEASE ENTER ORACLE_SID AS THE FIRST COMMAND LINE ARGUMENT    #"
echo "#         SCRIPT USAGE : make_me_primary.sh          #"
echo "##################################################################"
echo ""
exit
fi

ORACLE_SID=`echo $1 |tr '[A-Z]' '[a-z]'`; export ORACLE_SID;

ls -l /var/opt/oracle/cronjobs/set$ORACLE_SID > /dev/null
if [ $? != 0 ]
then
echo ""
echo "##################################################################"
echo "#           ENVIRONMENT SETTING SET FILE NOT FOUND...!!!         #"
echo "#           /var/opt/oracle/cronjobs/set$ORACLE_SID              #"
echo "##################################################################"
echo ""
exit
fi

. /var/opt/oracle/cronjobs/set$ORACLE_SID

DB=`echo $1 |tr '[a-z]' '[A-Z]'`; export DB;

sqlplus  -s /nolog |&
print -p  "connect / as sysdba"
print -p  "set feedback off pause off pagesize 0 heading off verify off linesize 500 term off"
print -p  "set sqlprompt ''"
read  -p   JUNK
print -p  "SELECT DATABASE_ROLE DBROLE FROM V\$DATABASE;"
read  -p   DBROLE
print -p  "exit"

if [ "$DBROLE" = "PRIMARY"  ]
then
echo ""
echo "##################################################################"
echo "#   ERROR ! ! ! NOT STANDBY DATABASE, PLEASE RUN IT ON STANDBY   #"
echo "##################################################################"
echo ""
exit
fi

echo ""
echo "##################################################################"
echo "#         SWITCHING $DB TO PRIMARY ROLE, PLEASE CONFIRM ...      #"
echo "##################################################################"
echo ""
echo "Continue? - Please enter 'Y' to proceed & 'N' to exit"
read ans
if [ "$ans" = 'Y' -o "$ans" = 'y' ]
then
sqlplus -s /nolog < /tmp/make_me_primary.log
connect / as sysdba;
alter database commit to switchover to primary with session shutdown;
shutdown immediate;
startup mount;
alter system set log_archive_dest_state_2=enable scope=both;
alter database set standby database to maximize performance;
alter database open;
select database_role from v\$database;
EOF
cat /tmp/make_me_primary.log
$ORACLE_HOME/bin/lsnrctl start PRIMARY_$DB
else
echo "Quitting ....."
exit
fi

echo "####################################################################"
echo "# PLEASE CONFIRM THAT THE STATUS OF DATABASE IS NOW "PRIMARY"      #"
echo "#                                                                  #"
echo "# On NEW STANDBY Host please run the following script:             #"
echo "# /var/opt/oracle/dataguard/start_recovery.sh                 #"
echo "####################################################################"
start_recovery.sh

#!/bin/ksh

if [ "$1" = "" ]
then
echo ""
echo "##################################################################"
echo "#   PLEASE ENTER ORACLE_SID AS THE FIRST COMMAND LINE ARGUMENT   #"
echo "#      SCRIPT USAGE : start_recovery.sh              #"
echo "##################################################################"
echo ""
exit
fi

ORACLE_SID=`echo $1 |tr '[A-Z]' '[a-z]'`; export ORACLE_SID;

ls -l /var/opt/oracle/cronjobs/set$ORACLE_SID > /dev/null
if [ $? != 0 ]
then
echo ""
echo "##################################################################"
echo "#           ENVIRONMENT SETTING SET FILE NOT FOUND...!!!         #"
echo "#           /var/opt/oracle/cronjobs/set$ORACLE_SID              #"
echo "##################################################################"
echo ""
exit
fi

. /var/opt/oracle/cronjobs/set$ORACLE_SID

DB=`echo $1 |tr '[a-z]' '[A-Z]'`; export DB;

sqlplus  -s /nolog |&
print -p  "connect / as sysdba"
print -p  "set feedback off pause off pagesize 0 heading off verify off linesize 500 term off"
print -p  "set sqlprompt ''"
read  -p   JUNK
print -p  "SELECT DATABASE_ROLE DBROLE FROM V\$DATABASE;"
read  -p   DBROLE
print -p  "exit"

if [ "$DBROLE" = "PRIMARY"  ]
then
echo ""
echo "##################################################################"
echo "#   ERROR ! ! ! NOT STANDBY DATABASE, PLEASE RUN IT ON STANDBY   #"
echo "##################################################################"
echo ""
exit
fi

echo ""
echo "##################################################################"
echo "#     STARTING RECOVERY FOR $DB  STANDBY, PLEASE CONFIRM ...     #"
echo "##################################################################"
echo ""
echo "Continue? - Please enter 'Y' to proceed & 'N' to exit"
read ans
if [ "$ans" = 'Y' -o "$ans" = 'y' ]
then
sqlplus -s /nolog < /tmp/start_recovery.log
connect / as sysdba;
recover managed standby database disconnect;
alter system set log_archive_dest_state_2=defer scope=both;
EOF
cat /tmp/start_recovery.log
ps -ef | grep ora_mrp0_$ORACLE_SID |grep -v grep > /dev/null
if [ $? != 0 ]
then
echo ""
echo "##################################################################"
echo "#           RECOVERY PROCESS NOT RUNNING... PLEASE CHECK         #"
echo "##################################################################"
echo ""
exit
else
echo "##################################################################"
echo "#           MRP PROCESS SUCESSFULLY STARTED                      #"
echo "##################################################################"
echo ""
echo "####################################################################"
echo "# 		SWITCHOVER COMPLETE                              #"
echo ""
echo "* Perform Database Post-Switchover Checklist!                      "
echo "####################################################################"
fi
else
echo "Quitting ....."
exit
fi

Posted in High Availability, Scripts, Unix | Tagged: , | Leave a Comment »

Script – Latch Contention (top 5 latches)

Posted by Gavin Soorma on July 6, 2009

This script will display the top 5 latches with the most sleeps.

Script can be changed to even sort the display on misses instead.

set linesize 120
col name format a30

select * from
 (select name, gets,misses,  sleeps
 from   v$latch
 order by sleeps desc)
 where rownum < 6;

Posted in Performance Tuning, Scripts | Tagged: , , , | Leave a Comment »

Script – Top SQL (Physical Reads)

Posted by Gavin Soorma on July 6, 2009

This script will list the top 5 SQL statements sorted by the most number of physical reads

set serverout on size 1000000
set feedback off
declare
top5 number;
text1 varchar2(4000);
x number;
len1 number;
Cursor c1 is
select disk_reads,substr(sql_text,1,4000)
from v$sqlarea
order by disk_reads desc;
begin
dbms_output.put_line('Reads'||' '||' Text');
dbms_output.put_line ('-----'||' '||'----------------------------------------------------');
dbms_output.put_line(' ');
open c1;
for i in 1 .. 5 loop
fetch c1 into top5, text1;
dbms_output.put_line(rpad(to_char(top5),9)|| ' '||substr(text1,1,66));
len1 :=length(text1);
x := 66;
while len1 > x-1 loop
dbms_output.put_line('" '||substr(text1,x,64));
x := x+64;
end loop;
end loop;
end;
/

Posted in Performance Tuning, Scripts | Tagged: , , | Leave a Comment »

Script – Top SQL (Buffer Gets)

Posted by Gavin Soorma on July 6, 2009

This script will list the top 5 SQL statements sorted by the most number of buffer gets or logical reads

set serverout on size 1000000

declare
top5 number;
text1 varchar2(4000);
x number;
len1 number;
Cursor c1 is
select buffer_gets,substr(sql_text,1,4000)
from v$sqlarea
order by buffer_gets desc;
begin
dbms_output.put_line('Reads'||'  '||'                          Text');
dbms_output.put_line ('-----'||'  '||'---------------------------------------------------');
dbms_output.put_line('      ');
open c1;
for i in 1 .. 5 loop
fetch c1 into top5, text1;
dbms_output.put_line(rpad(to_char(top5),9)|| ' '||substr(text1,1,66));
len1 :=length(text1);
x := 66;
while len1 > x-1 loop
dbms_output.put_line('"         '||substr(text1,x,64));
x := x+64;
end loop;
end loop;
end;
/

Posted in Performance Tuning, Scripts | Tagged: , , | Leave a Comment »

Script – Segments with highest I/O activity

Posted by Gavin Soorma on July 6, 2009

This script will list the top 10 segments in the database that have the most number of
physical reads against them.
Script can also be changed to query on 'physical writes' instead.

set pagesize 200
setlinesize 120
col segment_name format a20
col owner format a10 

select segment_name,object_type,total_physical_reads
from ( select owner||'.'||object_name as segment_name,object_type,
value as total_physical_reads
from v$segment_statistics
where statistic_name in ('physical reads')
order by total_physical_reads desc)
where rownum <=10;

Posted in Administration, Performance Tuning, Scripts | Tagged: , , , | Leave a Comment »

Script – List status of all submitted DBMS jobs

Posted by Gavin Soorma on July 3, 2009

set pagesize 100
set linesize 120
ttitle -
  center  'Submitted DBMS Jobs' skip 2

col job  format 99999  heading 'job#'
col subu format a10  heading 'Submitter'     trunc
col lsd  format a5   heading 'Last|Ok|Date'
col lst  format a5   heading 'Last|Ok|Time'
col nrd  format a5   heading 'Next|Run|Date'
col nrt  format a5   heading 'Next|Run|Time'
col fail format 999  heading 'Errs'
col ok   format a2   heading 'Ok'

select
  job,
  log_user                   subu,
  what                       proc,
  to_char(last_date,'MM/DD') lsd,
  substr(last_sec,1,5)       lst,
  to_char(next_date,'MM/DD') nrd,
  substr(next_sec,1,5)       nrt,
  failures                   fail,
  decode(broken,'Y','N','Y') ok
from
  sys.dba_jobs;

Posted in Scripts | Tagged: , , , | Leave a Comment »

Script – What Wait Events Are Sessions Waiting On

Posted by Gavin Soorma on July 2, 2009

set linesize 120
col username format a10
col event format a30
 
select sid, serial#,username, event,
seconds_in_wait, wait_time
from v$session where state = 'WAITING'
and wait_class != 'Idle'
order by event
;

Posted in Performance Tuning, Scripts | Tagged: , , | Leave a Comment »

Script – Sessions Waiting On A Particular Wait Event

Posted by Gavin Soorma on July 2, 2009

SELECT count(*), event
FROM v$session_wait
WHERE wait_time = 0
AND event NOT IN ('smon timer','pipe get','wakeup time manager',
'pmon timer','rdbms ipc message', 'SQL*Net message from client')
GROUP BY event
ORDER BY 1 DESC;

Posted in Performance Tuning, Scripts | Tagged: , , | Leave a Comment »

Script – Datafiles with highest I/O activity

Posted by Gavin Soorma on July 1, 2009

col name format a40
set linesize 140
select * from (
select name,phyrds, phywrts,readtim,writetim
from v$filestat a, v$datafile b
where a.file#=b.file#
order by readtim desc) where rownum <6;

Posted in Performance Tuning, Scripts | Tagged: , , , , | Leave a Comment »

Script – Find SQL being executed by a OS Process ID (PID)

Posted by Gavin Soorma on July 1, 2009

prompt "Please Enter The UNIX Process ID"
set pagesize 50000
set linesize 30000
set long 500000
set head off
select
s.username su,
substr(sa.sql_text,1,540) txt
from v$process p,
v$session s,
v$sqlarea sa
where p.addr=s.paddr
and s.username is not null
and s.sql_address=sa.address(+)
and s.sql_hash_value=sa.hash_value(+)
and spid=&SPID;

Posted in Scripts | Tagged: , , , , | Leave a Comment »

Script – List SQL being executed by a particular SID

Posted by Gavin Soorma on July 1, 2009

col sql_text format a100 heading "Current SQL"
select q.sql_text
from v$session s
, v$sql q
WHERE s.sql_address = q.address
and s.sql_hash_value + DECODE
(SIGN(s.sql_hash_value), -1, POWER( 2, 32), 0) = q.hash_value
AND s.sid=&1;

Posted in Scripts | Tagged: , , | Leave a Comment »

Script – Monitor sessions with high Physical Reads

Posted by Gavin Soorma on July 1, 2009

set linesize 120
col osuser format a10
col username format 10
select
OSUSER osuser,
username,
PROCESS pid,
ses.SID sid,
SERIAL#,
PHYSICAL_READS,
BLOCK_CHANGES
from v$session ses,
v$sess_io sio
where ses.SID = sio.SID
order by PHYSICAL_READS;

Posted in Scripts | Tagged: , , | Leave a Comment »

Script – Query the RMAN catalog to list backup completion status

Posted by Gavin Soorma on July 1, 2009

Note – run this query connected as the owner of the RMAN catalog

set lines 80

set pages 250

ttitle "Daily Backup........"

select DB NAME,dbid,NVL(TO_CHAR(max(backuptype_db),'DD/MM/YYYY HH24:MI'),'01/01/0001:00:00') DBBKP,
NVL(TO_CHAR(max(backuptype_arch),'DD/MM/YYYY HH24:MI'),'01/01/0001:00:00') ARCBKP
from (
select a.name DB,dbid,
decode(b.bck_type,'D',max(b.completion_time),'I', max(b.completion_time)) BACKUPTYPE_db,
decode(b.bck_type,'L',max(b.completion_time)) BACKUPTYPE_arch
from rc_database a,bs b
where a.db_key=b.db_key
and b.bck_type is not null
and b.bs_key not in(Select bs_key from rc_backup_controlfile where AUTOBACKUP_DATE
is not null or AUTOBACKUP_SEQUENCE is not null)
and b.bs_key not in(select bs_key from rc_backup_spfile)
group by a.name,dbid,b.bck_type
) group by db,dbid
ORDER BY least(to_date(DBBKP,'DD/MM/YYYY HH24:MI'),to_date(ARCBKP,'DD/MM/YYYY HH24:MI'))
/

Posted in Scripts | Tagged: , , , | Leave a Comment »

Script – List all recent DDL modifications

Posted by Gavin Soorma on July 1, 2009

set pagesize 200 colsep ' '
col Owner format a20
col Object_Name format a30
col Last_DDL format a20
break on Owner
select Owner, Object_type
Object_Name,
Timestamp Last_DDL
from DBA_OBJECTS
where  SysDate - TO_DATE(TimeStamp,'YYYY-MM-DD:HH24:MI:SS') < 1
order by Owner, Object_Name
/

Posted in Scripts | Tagged: , , , | Leave a Comment »

Script – List Objects being accessed by a particular SID

Posted by Gavin Soorma on July 1, 2009

set pagesize 300
select sid,serial#,username,status from v$session
WHERE USERNAME IS NOT NULL
order by STATUS DESC;
col sid format 999
col owner format a10
col object format a20
col type format a10
set linesize 300
/* ENTER THE SID TO CHECK */

select sid,owner,object,type
from v$access where sid = &sid
order by owner,type
;

Posted in Scripts | Tagged: , | Leave a Comment »

Script – Temporary tablespace usage

Posted by Arjun Raja on June 30, 2009

Listing of temp segments.

SELECT A.tablespace_name tablespace, D.mb_total,
SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_used,
D.mb_total – SUM (A.used_blocks * D.block_size) / 1024 / 1024 mb_free
FROM v$sort_segment A,
(
SELECT B.name, C.block_size, SUM (C.bytes) / 1024 / 1024 mb_total
FROM v$tablespace B, v$tempfile C
WHERE B.ts#= C.ts#
GROUP BY B.name, C.block_size
) D
WHERE A.tablespace_name = D.name
GROUP by A.tablespace_name, D.mb_total;

Temp segment usage per session.

SELECT S.sid || ‘,’ || S.serial# sid_serial, S.username, S.osuser, P.spid, S.module,
P.program, SUM (T.blocks) * TBS.block_size / 1024 / 1024 mb_used, T.tablespace,
COUNT(*) statements
FROM v$sort_usage T, v$session S, dba_tablespaces TBS, v$process P
WHERE T.session_addr = S.saddr
AND S.paddr = P.addr
AND T.tablespace = TBS.tablespace_name
GROUP BY S.sid, S.serial#, S.username, S.osuser, P.spid, S.module,
P.program, TBS.block_size, T.tablespace
ORDER BY sid_serial;

Posted in Monitoring, Scripts | Tagged: , , , | 1 Comment »

Monitor long running operations using v$session_longops

Posted by Gavin Soorma on June 30, 2009

SELECT SID, SERIAL#, opname, SOFAR, TOTALWORK,
ROUND(SOFAR/TOTALWORK*100,2) COMPLETE
FROM   V$SESSION_LONGOPS
WHERE
TOTALWORK != 0
AND    SOFAR != TOTALWORK
order by 1;

Note: the same query can be used to monitor RMAN backup status

SELECT SID, SERIAL#, CONTEXT, SOFAR, TOTALWORK,
       ROUND(SOFAR/TOTALWORK*100,2) "%_COMPLETE"
FROM V$SESSION_LONGOPS
WHERE OPNAME LIKE 'RMAN%'
  AND OPNAME NOT LIKE '%aggregate%'
  AND TOTALWORK != 0
  AND SOFAR  != TOTALWORK
;

       SID    SERIAL# OPNAME                    SOFAR  TOTALWORK   COMPLETE
---------- ---------- -------------------- ---------- ---------- ----------
       604      13371 Table Scan                 6311      24498      25.76
       685       1586 Table Scan                 6333      24498      25.85

Posted in Administration, Monitoring, Scripts | Tagged: , , , | Leave a Comment »

Monitor Data Guard Log Shipping

Posted by Gavin Soorma on June 30, 2009

Note: This query needs to be run on the Primary database.

SET PAGESIZE 124
COL DB_NAME FORMAT A8
COL HOSTNAME FORMAT A12
COL LOG_ARCHIVED FORMAT 999999
COL LOG_APPLIED FORMAT 999999
COL LOG_GAP FORMAT 9999
COL APPLIED_TIME FORMAT A12
SELECT DB_NAME, HOSTNAME, LOG_ARCHIVED, LOG_APPLIED,APPLIED_TIME,
LOG_ARCHIVED-LOG_APPLIED LOG_GAP
FROM
(
SELECT NAME DB_NAME
FROM V$DATABASE
),
(
SELECT UPPER(SUBSTR(HOST_NAME,1,(DECODE(INSTR(HOST_NAME,'.'),0,LENGTH(HOST_NAME),
(INSTR(HOST_NAME,'.')-1))))) HOSTNAME
FROM V$INSTANCE
),
(
SELECT MAX(SEQUENCE#) LOG_ARCHIVED
FROM V$ARCHIVED_LOG WHERE DEST_ID=1 AND ARCHIVED='YES'
),
(
SELECT MAX(SEQUENCE#) LOG_APPLIED
FROM V$ARCHIVED_LOG WHERE DEST_ID=2 AND APPLIED='YES'
),
(
SELECT TO_CHAR(MAX(COMPLETION_TIME),'DD-MON/HH24:MI') APPLIED_TIME
FROM V$ARCHIVED_LOG WHERE DEST_ID=2 AND APPLIED='YES'
);

DB_NAME  HOSTNAME     LOG_ARCHIVED LOG_APPLIED APPLIED_TIME LOG_GAP
-------- ------------ ------------ ----------- ------------ -------
CPSPRD   PRDU009N1           11213       11213 30-JUN/08:48       0

Posted in Monitoring, Scripts | Tagged: , , | Leave a Comment »

Identify active transactions in undo and rollback segments

Posted by Gavin Soorma on June 29, 2009

col o format a10
col u format a10
select osuser o, username u, sid,
segment_name s, substr(sa.sql_text,1,200) txt
from v$session s,
v$transaction t,
dba_rollback_segs r,
v$sqlarea sa
where s.taddr=t.addr
and t.xidusn=r.segment_id(+)
and s.sql_address=sa.address(+)
And substr(sa.sql_text,1,200) is not null
order by 3;

col name format a8
col username format a8
col osuser format a8
col start_time format a17
col status format a12
tti 'Active transactions'
select username, osuser,
t.start_time, r.name, t.used_ublk "ROLLB BLKS",
decode(t.space, 'YES', 'SPACE TX',
decode(t.recursive, 'YES', 'RECURSIVE TX',
decode(t.noundo, 'YES', 'NO UNDO TX', t.status)
)) status
from sys.v_$transaction t, sys.v_$rollname r, sys.v_$session s
where t.xidusn = r.usn
and t.ses_addr = s.saddr
/

Posted in Monitoring, Scripts | Tagged: , , , | Leave a Comment »

Locked Sessions and Locked Objects

Posted by Gavin Soorma on June 29, 2009

PROMPT Blocked and Blocker Sessions

col blocker_sid format 99999999999
col blocked_sid format 99999999999
col min_blocked format 99999999999
col request format 9999999
select /*+ ORDERED */
blocker.sid blocker_sid
, blocked.sid blocked_sid
, TRUNC(blocked.ctime/60) min_blocked
, blocked.request
from (select *
from v$lock
where block != 0
and type = 'TX') blocker
, v$lock blocked
where
blocked.type='TX'
and blocked.block = 0
and blocked.id1 = blocker.id1;

prompt blocked objects from V$LOCK and SYS.OBJ$

set lines 132
col BLOCKED_OBJ format a35 trunc
select /*+ ORDERED */
l.sid
, l.lmode
, TRUNC(l.ctime/60) min_blocked
, u.name||'.'||o.NAME blocked_obj
from (select *
from v$lock
where type='TM'
and sid in (select sid
from v$lock
where block!=0)) l
, sys.obj$ o
, sys.user$ u
where o.obj# = l.ID1
and o.OWNER# = u.user#
/

prompt blocked sessions from V$LOCK

select /*+ ORDERED */
blocker.sid blocker_sid
, blocked.sid blocked_sid
, TRUNC(blocked.ctime/60) min_blocked
, blocked.request
from (select *
from v$lock
where block != 0
and type = 'TX') blocker
, v$lock blocked
where blocked.type='TX'
and blocked.block = 0
and blocked.id1 = blocker.id1
/

prompt blokers session details from V$SESSION

set lines 132
col username format a10 trunc
col osuser format a12 trunc
col machine format a15 trunc
col process format a15 trunc
col action format a50 trunc
SELECT sid
, serial#
, username
, osuser
, machine
FROM v$session
WHERE sid IN (select sid
from v$lock
where block != 0
and type = 'TX')
/

Posted in Monitoring, Scripts | Tagged: , , , , | Leave a Comment »

Identify database idle sessions

Posted by Gavin Soorma on June 29, 2009

set linesize 140
col username format a15
col idle format a15
col program format a30

PROMPT Enter the number of minutes for which the sessions should have been idle:
PROMPT

select
sid,username,status,
to_char(logon_time,'dd-mm-yy hh:mi:ss') "LOGON",
floor(last_call_et/3600)||':'||
floor(mod(last_call_et,3600)/60)||':'||
mod(mod(last_call_et,3600),60) "IDLE",
program
from
v$session
where
type='USER'
and (LAST_CALL_ET / 60) > &minutes
order by last_call_et;

Posted in Scripts | Leave a Comment »

Identify database SID based on OS Process ID

Posted by Gavin Soorma on June 29, 2009

col sid format 999999
col username format a20
col osuser format a15
select b.spid,a.sid, a.serial#,a.username, a.osuser
from v$session a, v$process b
where a.paddr= b.addr
and b.spid='&spid'
order by b.spid;

Posted in Scripts | Tagged: , , | Leave a Comment »

Identify OS process ID based on database SID

Posted by Gavin Soorma on June 29, 2009

col sid format 999999
col username format a20
col osuser format a15
select a.sid, a.serial#,a.username, a.osuser, b.spid
from v$session a, v$process b
where a.paddr= b.addr
and a.sid='&sid'
order by a.sid;

Posted in Scripts | Tagged: , , | Leave a Comment »

List all tablespaces with free space < 10%

Posted by Gavin Soorma on June 29, 2009

set pagesize 300
set linesize 100
column tablespace_name format a15 heading 'Tablespace'
column sumb format 999,999,999
column extents format 9999
column bytes format 999,999,999,999
column largest format 999,999,999,999
column Tot_Size format 999,999 Heading 'Total Size(Mb)'
column Tot_Free format 999,999,999 heading 'Total Free(Kb)'
column Pct_Free format 999.99 heading '% Free'
column Max_Free format 999,999,999 heading 'Max Free(Kb)'
column Min_Add format 999,999,999 heading 'Min space add (MB)'

ttitle center 'Tablespaces With Less Than 10% Free Space' skip 2
set echo off 

select a.tablespace_name,sum(a.tots/1048576) Tot_Size,
sum(a.sumb/1024) Tot_Free,
sum(a.sumb)*100/sum(a.tots) Pct_Free,
ceil((((sum(a.tots) * 15) - (sum(a.sumb)*100))/85 )/1048576) Min_Add
from
(
select tablespace_name,0 tots,sum(bytes) sumb
from dba_free_space a
group by tablespace_name
union
select tablespace_name,sum(bytes) tots,0 from
dba_data_files
group by tablespace_name) a
group by a.tablespace_name
having sum(a.sumb)*100/sum(a.tots) < 10
order by pct_free;

Posted in Scripts | Leave a Comment »

Monitor the Flashback area space usage

Posted by Gavin Soorma on June 29, 2009

SELECT * FROM   V$FLASH_RECOVERY_AREA_USAGE; 

SELECT * FROM V$RECOVERY_FILE_DEST; 

col ROUND(SPACE_LIMIT/1048576) heading "Space Allocated (MB)" format 999999
col round(space_used/1048576) heading "Space Used (MB)" format 99999
col name format a40

select name, round(space_limit/1048576),round(space_used/1048576)
from  v$RECOVERY_FILE_DEST;

Posted in Scripts | Tagged: , , , | Leave a Comment »

Identify ‘hot’ objects when faced with ‘Cache Buffers Chains Latch’ wait event

Posted by Gavin Soorma on June 29, 2009

select
   count(*)    child_count,
   sum(gets)   sum_gets,
   sum(misses) sum_misses,
   sum(sleeps) sum_sleeps
from
   v$latch_children
where
   name = 'cache buffers chains';

select
   p1 "File #".
   p2 "Block #"
from
   v$session_wait
where
   event ='cache buffer chains';

select
   owner,
   segment_name,
   segment_type
from
   dba_extents
where
   file_id = &P1
and
 &P2 between block_id and block_id + blocks -1;

col object_name format a20
col owner format a10
col subobject_name format a20

select distinct o.owner, o.object_name, o.subobject_name, o.object_type
from dba_objects o, v$bh b
where o.data_object_id=b.objd and b.objd < power(2,22) and status != 'free'
  and b.file#=&P1
  and b.block#=&P2
;

Posted in Scripts | Tagged: , , , | Leave a Comment »

Monitor space used in ASM Disk Groups

Posted by Gavin Soorma on June 29, 2009

SET LINESIZE  145
SET PAGESIZE  9999
SET VERIFY    off
COLUMN group_name             FORMAT a20           HEAD 'Disk Group|Name'
COLUMN sector_size            FORMAT 99,999        HEAD 'Sector|Size'
COLUMN block_size             FORMAT 99,999        HEAD 'Block|Size'
COLUMN allocation_unit_size   FORMAT 999,999,999   HEAD 'Allocation|Unit Size'
COLUMN state                  FORMAT a11           HEAD 'State'
COLUMN type                   FORMAT a6            HEAD 'Type'
COLUMN total_mb               FORMAT 999,999,999   HEAD 'Total Size (MB)'
COLUMN used_mb                FORMAT 999,999,999   HEAD 'Used Size (MB)'
COLUMN pct_used               FORMAT 999.99        HEAD 'Pct. Used'

break on report on disk_group_name skip 1
compute sum label "Grand Total: " of total_mb used_mb on report

SELECT
    name                                     group_name
  , sector_size                              sector_size
  , block_size                               block_size
  , allocation_unit_size                     allocation_unit_size
  , state                                    state
  , type                                     type
  , total_mb                                 total_mb
  , (total_mb - free_mb)                     used_mb
  , ROUND((1- (free_mb / total_mb))*100, 2)  pct_used
FROM
    v$asm_diskgroup
ORDER BY
    name
/

Posted in Administration, Scripts | Tagged: , , , | Leave a Comment »

Determing the optimal UNDO tablespace size

Posted by Gavin Soorma on June 24, 2009

SELECT d.undo_size/(1024*1024) “ACTUAL UNDO SIZE [MByte]“,
       SUBSTR(e.value,1,25) “UNDO RETENTION [Sec]“,
       (TO_NUMBER(e.value) * TO_NUMBER(f.value) *
       g.undo_block_per_sec) / (1024*1024)
      “NEEDED UNDO SIZE [MByte]“
  FROM (
       SELECT SUM(a.bytes) undo_size
         FROM v$datafile a,
              v$tablespace b,
              dba_tablespaces c
        WHERE c.contents = 'UNDO'
          AND c.status = 'ONLINE'
          AND b.name = c.tablespace_name
          AND a.ts# = b.ts#
       ) d,
      v$parameter e,
       v$parameter f,
       (
       SELECT MAX(undoblks/((end_time-begin_time)*3600*24))
         undo_block_per_sec
         FROM v$undostat
       ) g
 WHERE e.name = 'undo_retention'
  AND f.name = 'db_block_size'
/

set feedback off
set heading off
set lines 132
declare
  cursor get_undo_stat is
         select d.undo_size/(1024*1024) "C1",
                substr(e.value,1,25)    "C2",
                (to_number(e.value) * to_number(f.value) *
g.undo_block_per_sec) / (1024*1024) "C3",
                round((d.undo_size / (to_number(f.value) *
g.undo_block_per_sec)))             "C4"
           from (select sum(a.bytes) undo_size
                   from v$datafile      a,
                        v$tablespace    b,
                        dba_tablespaces c
                  where c.contents = 'UNDO'
                    and c.status = 'ONLINE'
                    and b.name = c.tablespace_name
                    and a.ts# = b.ts#)  d,
                v$parameter e,
                v$parameter f,
                (select max(undoblks/((end_time-begin_time)*3600*24))
undo_block_per_sec from v$undostat)  g
          where e.name = 'undo_retention'
            and f.name = 'db_block_size';
begin
dbms_output.put_line(chr(10)||chr(10)||chr(10)||chr(10) ||
'To optimize UNDO you have two choices :');
dbms_output.put_line('==================================================
==' || chr(10));
  for rec1 in get_undo_stat loop
      dbms_output.put_line('A)
Adjust UNDO tablespace size according to UNDO_RETENTION :'
|| chr(10));
      dbms_output.put_line(rpad('ACTUAL UNDO SIZE ',65,'.')|| ' : ' ||
TO_CHAR(rec1.c1,'999999') || ' MEGS');
      dbms_output.put_line(rpad('OPTIMAL UNDO SIZE WITH ACTUAL UNDO_RETENTION
(' || ltrim(TO_CHAR(rec1.c2/60,'999999'))
 || ' MINUTES)
',65,'.') || ' : ' || TO_CHAR(rec1.c3,'999999') || ' MEGS');
      dbms_output.put_line(chr(10));
      dbms_output.put_line('B) Adjust UNDO_RETENTION according to UNDO tablespace size :'
|| chr(10));
      dbms_output.put_line(rpad('ACTUAL UNDO RETENTION ',65,'.') ||
' : ' || TO_CHAR(rec1.c2/60,'999999') || ' MINUTES');
      dbms_output.put_line(rpad('OPTIMAL UNDO RETENTION WITH ACTUAL UNDO SIZE
(' || ltrim(TO_CHAR(rec1.c1,'999999')) || ' MEGS) ',65,'.') || ' : ' ||
TO_CHAR(rec1.c4/60,'999999') || ' MINUTES');
  end loop;
dbms_output.put_line(chr(10)||chr(10));
end;
/

select 'Number of "ORA-01555 (Snapshot too old)" encountered since
the last startup of the instance : ' || sum(ssolderrcnt)
from v$undostat;

Posted in Administration, Administration, Scripts | Tagged: , , | Leave a Comment »

Query the RMAN catalog to check backup status

Posted by Gavin Soorma on June 23, 2009

This script will query the RMAN catalog and report on the backup status of every database in the catalog.

 

set lines 80
set pages 250
ttitle "Daily Backup........"
select DB NAME,dbid,
NVL(TO_CHAR(max(backuptype_db),'DD/MM/YYYY HH24:MI'),'01/01/0001:00:00') DBBKP,
NVL(TO_CHAR(max(backuptype_arch),'DD/MM/YYYY HH24:MI'),'01/01/0001:00:00') ARCBKP
from (
select a.name DB,dbid,
decode(b.bck_type,'D',max(b.completion_time),'I',
max(b.completion_time)) BACKUPTYPE_db,
decode(b.bck_type,'L',
max(b.completion_time)) BACKUPTYPE_arch
from rc_database a,bs b
where a.db_key=b.db_key
and b.bck_type is not null
and b.bs_key not in(Select bs_key from rc_backup_controlfile
where AUTOBACKUP_DATE is not null or AUTOBACKUP_SEQUENCE is not null)
and b.bs_key not in(select bs_key from rc_backup_spfile)
group by a.name,dbid,b.bck_type
) group by db,dbid
ORDER BY least(to_date(DBBKP,'DD/MM/YYYY HH24:MI'),
to_date(ARCBKP,'DD/MM/YYYY HH24:MI'));
 

Posted in Administration, Scripts | Leave a Comment »

Script- Track redo generation by day

Posted by Gavin Soorma on June 20, 2009


select trunc(completion_time) rundate
,count(*)  logswitch
,round((sum(blocks*block_size)/1024/1024)) "REDO PER DAY (MB)"
from v$archived_log
group by trunc(completion_time)
order by 1;

Posted in Monitoring, Scripts | Tagged: , , , | Leave a Comment »

Recompiling Objects based on dependencies

Posted by Gavin Soorma on June 20, 2009

In order to prevent you from the task from running a recompile script several times so as compile all objects that are dependant on other objects, we need to take into account the dependency of objects – this is maintained by the view DEPENDENCY$ in the SYS schema.

 This script was taken by me from one of the Honeywell DBA’s when he was working on the CORE migration and it works really well. You need to pass the parameter of the schema owner name to the script.

 set verify off

set head off

set feed off

set pages 999

 create table temp_depend (object_id,referenced_object_id) as

select d.d_obj#, d.p_obj# from dependency$ d

where d.d_obj# in (select object_id from dba_objects

      where owner = ‘&&uname’

  and object_type in (‘FUNCTION’, ‘PROCEDURE’, ‘PACKAGE’, ‘PACKAGE BODY’, ‘VIEW’

, ‘TRIGGER’) and status=’INVALID’)

/

 create or replace view ord_obj_by_depend (dlevel, object_id) as

select max(level), object_id from temp_depend

connect by object_id = prior referenced_object_id

group by object_id

/

 –spool &filename

spool compile.sql

 select

decode(OBJECT_TYPE, ‘PACKAGE BODY’,

‘alter package ‘ || OWNER||’.'||OBJECT_NAME || ‘ compile body;’,

‘alter ‘ || OBJECT_TYPE || ‘ ‘ || OWNER||’.'||OBJECT_NAME || ‘ compile;’)

from dba_objects a, ord_obj_by_depend b

where a.owner = upper(‘&&uname’) and

status=’INVALID’

and

A.OBJECT_ID = B.OBJECT_ID(+) and

OBJECT_TYPE in (‘PACKAGE BODY’, ‘PACKAGE’, ‘FUNCTION’, ‘PROCEDURE’, ‘TRIGGER’,

VIEW’)

order by DLEVEL DESC, OBJECT_TYPE, OBJECT_NAME;

 

spool off

PROMPT

PROMPT COMPILING INVALID OBJECTS ….

PROMPT

@compile.sql

 drop view ord_obj_by_depend;

drop table temp_depend;

undef uname

set head on

set feed on

set pages 24

set verify on

Posted in Administration, Scripts | Leave a Comment »

Using DBMS_SCHEDULER to run a UNIX shell script

Posted by Gavin Soorma on June 18, 2009

CREATE A PROGRAM

begin

dbms_scheduler.create_program

(

program_name => ‘UPDATE_VERITAS’,

program_type => ‘EXECUTABLE’,

program_action => ‘/opt/oracle/scripts/blade08/update_veritas.sh’,

enabled => TRUE,

comments => ‘Check the Time’

);

end;

/

 CREATE A SCHEDULE
 

begin

dbms_scheduler.create_schedule

(

schedule_name => ‘EVERY_6_HOURS’,

repeat_interval => ‘FREQ=HOURLY; INTERVAL=6′,

comments => ‘Every 6 Hours’

);

end;

/

 
CREATE A JOB
 

begin

dbms_scheduler.create_job

(

job_name => ‘RUN_UPDATE_VERITAS’,

program_name => ‘UPDATE_VERITAS’,

schedule_name => ‘EVERY_6_HOURS’,

comments => ‘Run the program UPDATE_VERITAS every 6 Hours’,

enabled => TRUE

);

end;

/

 

RUN THE JOB MANUALLY

exec dbms_scheduler.run_job(’RUN_UPDATE_VERITAS’);

 
Check the job run status and other details      
 

select log_id, log_date, job_name, status, error#, additional_info
 from dba_scheduler_job_run_details
where job_name =’RUN_UPDATE_VERITAS’;

Posted in Administration, Administration, Scripts | Tagged: , , | 1 Comment »

Trigger to use with Data Guard to change service name

Posted by Gavin Soorma on June 18, 2009

CREATE OR REPLACE TRIGGER manage_OCIservice
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(‘apex_dg’);
ELSE
DBMS_SERVICE.STOP_SERVICE(‘apex_dg’);
END IF;
END;
/

Posted in Administration, Scripts | Leave a Comment »

Redo Log File Switches – By hour of the day

Posted by Gavin Soorma on June 18, 2009

prompt
prompt "Morning .........."
select to_char(first_time,'DD/MON') day,
to_char(sum(decode(to_char(first_time,'HH24'),'07',1,0)),'000')"07",
to_char(sum(decode(to_char(first_time,'HH24'),'08',1,0)),'000')"08",
to_char(sum(decode(to_char(first_time,'HH24'),'09',1,0)),'000')"09",
to_char(sum(decode(to_char(first_time,'HH24'),'10',1,0)),'000')"10",
to_char(sum(decode(to_char(first_time,'HH24'),'11',1,0)),'000')"11",
to_char(sum(decode(to_char(first_time,'HH24'),'12',1,0)),'000')"12",
to_char(sum(decode(to_char(first_time,'HH24'),'13',1,0)),'000')"13",
to_char(sum(decode(to_char(first_time,'HH24'),'14',1,0)),'000')"14",
to_char(sum(decode(to_char(first_time,'HH24'),'15',1,0)),'000')"15",
to_char(sum(decode(to_char(first_time,'HH24'),'16',1,0)),'000')"16",
to_char(sum(decode(to_char(first_time,'HH24'),'17',1,0)),'000')"17",
to_char(sum(decode(to_char(first_time,'HH24'),'18',1,0)),'000')"18"
from v$log_history
WHERE TRUNC(FIRST_TIME) > TRUNC(SYSDATE) - 7
group by to_char(first_time,'DD/MON');
prompt
prompt
Prompt "Evening ........"
prompt
select to_char(first_time,'DD/MON') day,
to_char(sum(decode(to_char(first_time,'HH24'),'19',1,0)),'000')"19",
to_char(sum(decode(to_char(first_time,'HH24'),'20',1,0)),'000')"20",
to_char(sum(decode(to_char(first_time,'HH24'),'21',1,0)),'000')"21",
to_char(sum(decode(to_char(first_time,'HH24'),'22',1,0)),'000')"22",
to_char(sum(decode(to_char(first_time,'HH24'),'23',1,0)),'000')"23",
to_char(sum(decode(to_char(first_time,'HH24'),'00',1,0)),'000') "00",
to_char(sum(decode(to_char(first_time,'HH24'),'01',1,0)),'000')"01",
to_char(sum(decode(to_char(first_time,'HH24'),'02',1,0)),'000')"02",
to_char(sum(decode(to_char(first_time,'HH24'),'03',1,0)),'000')"03",
to_char(sum(decode(to_char(first_time,'HH24'),'04',1,0)),'000')"04",
to_char(sum(decode(to_char(first_time,'HH24'),'05',1,0)),'000')"05",
to_char(sum(decode(to_char(first_time,'HH24'),'06',1,0)),'000')"06"
from v$log_history
WHERE TRUNC(FIRST_TIME) > TRUNC(SYSDATE) - 7
group by to_char(first_time,'DD/MON');

Posted in Monitoring, Scripts | Tagged: , , , | Leave a Comment »

Check if block change tracking file is being used

Posted by Gavin Soorma on June 18, 2009


select file#, avg(datafile_blocks), avg(blocks_read), avg(blocks_read/datafile_blocks) * 100
as "% read for backup"
from v$backup_datafile
where incremental_level > 0 and used_change_tracking = 'YES'
group by file# order by file#;

Posted in Administration, Scripts | Leave a Comment »

Check for dependant foreign keys before dropping Primary Key

Posted by Gavin Soorma on June 18, 2009

SELECT A.owner foreign_owner, a.table_name foreign_table, b.owner primary_owner, b.table_name primary_table
from dba_constraints a, dba_constraints b
where a.r_constraint_name = b.constraint_name and a.constraint_type = 'R'
and b.constraint_type = 'P' and b.table_name = 'DEPT';

Posted in Administration, Scripts | Leave a Comment »