Translate into your own language

Showing posts with label Scripts. Show all posts
Showing posts with label Scripts. Show all posts

Tuesday, January 13, 2026

Script: Automated Reindexing of Indexes with Bloat > 30%

 #!/bin/bash

set -euo pipefail


# ================= CONFIG =================

PGDATABASE="<dbname>"

LOGFILE="/tmp/reindex_concurrently_$(date +%F_%H%M).log"


# DRY RUN mode:

# true  = only print commands (no execution)

# false = execute REINDEX commands

DRY_RUN=true


# Login command (runs psql as postgres user)

psql="psql -XqtA -d $PGDATABASE"

# ==========================================


echo "===== REINDEX CONCURRENTLY STARTED: $(date) =====" | tee -a "$LOGFILE"

echo "DRY_RUN = $DRY_RUN" | tee -a "$LOGFILE"


$psql <<'EOF' |

WITH btree_index_atts AS (

    SELECT

        nspname,

        indexclass.relname AS index_name,

        indexclass.reltuples,

        indexclass.relpages,

        indrelid,

        indexrelid,

        indexclass.relam,

        tableclass.relname AS tablename,

        regexp_split_to_table(indkey::text, ' ')::smallint AS attnum,

        indexrelid AS index_oid

    FROM pg_index

    JOIN pg_class AS indexclass ON pg_index.indexrelid = indexclass.oid

    JOIN pg_class AS tableclass ON pg_index.indrelid = tableclass.oid

    JOIN pg_namespace ON pg_namespace.oid = indexclass.relnamespace

    JOIN pg_am ON indexclass.relam = pg_am.oid

    WHERE pg_am.amname = 'btree'

      AND indexclass.relpages > 0

      AND nspname NOT IN ('pg_catalog','information_schema')

),

index_item_sizes AS (

    SELECT

        ind_atts.nspname,

        ind_atts.index_name,

        ind_atts.reltuples,

        ind_atts.relpages,

        ind_atts.relam,

        indrelid AS table_oid,

        index_oid,

        current_setting('block_size')::numeric AS bs,

        8 AS maxalign,

        24 AS pagehdr,

        CASE

            WHEN max(coalesce(pg_stats.null_frac,0)) = 0 THEN 2

            ELSE 6

        END AS index_tuple_hdr,

        SUM((1 - coalesce(pg_stats.null_frac, 0))

            * coalesce(pg_stats.avg_width, 1024)) AS nulldatawidth

    FROM pg_attribute

    JOIN btree_index_atts AS ind_atts

        ON pg_attribute.attrelid = ind_atts.indexrelid

       AND pg_attribute.attnum = ind_atts.attnum

    JOIN pg_stats

        ON pg_stats.schemaname = ind_atts.nspname

       AND (

            (pg_stats.tablename = ind_atts.tablename

             AND pg_stats.attname = pg_catalog.pg_get_indexdef(

                 pg_attribute.attrelid, pg_attribute.attnum, TRUE))

            OR

            (pg_stats.tablename = ind_atts.index_name

             AND pg_stats.attname = pg_attribute.attname)

        )

    WHERE pg_attribute.attnum > 0

    GROUP BY 1,2,3,4,5,6,7,8,9

),

index_aligned_est AS (

    SELECT

        maxalign, bs, nspname, index_name, reltuples,

        relpages, relam, table_oid, index_oid,

        COALESCE (

            CEIL (

                reltuples * (

                    6 + maxalign

                    - CASE

                        WHEN index_tuple_hdr % maxalign = 0 THEN maxalign

                        ELSE index_tuple_hdr % maxalign

                      END

                    + nulldatawidth

                    + maxalign

                    - CASE

                        WHEN nulldatawidth::int % maxalign = 0 THEN maxalign

                        ELSE nulldatawidth::int % maxalign

                      END

                )::numeric / (bs - pagehdr::numeric) + 1

            ),

            0

        ) AS expected

    FROM index_item_sizes

),

raw_bloat AS (

    SELECT

        nspname,

        index_name,

        bs * relpages::bigint AS totalbytes,

        expected,

        CASE

            WHEN relpages <= expected THEN 0

            ELSE (relpages - expected) * 100.0 / relpages

        END AS realbloat,

        bs * GREATEST(relpages - expected,0)::bigint AS wastedbytes

    FROM index_aligned_est

),

format_bloat AS (

    SELECT

        nspname AS schema_name,

        index_name,

        ROUND(realbloat) AS bloat_pct,

        ROUND(wastedbytes / (1024^3)::numeric, 3) AS bloat_gb

    FROM raw_bloat

)

SELECT

    'REINDEX INDEX CONCURRENTLY '

    || quote_ident(schema_name) || '.'

    || quote_ident(index_name) || ';'

FROM format_bloat

WHERE bloat_pct > 90

  AND bloat_gb > 0.01

ORDER BY bloat_gb DESC;

EOF

while read -r CMD

do

    [ -z "$CMD" ] && continue


    echo "--------------------------------------------" | tee -a "$LOGFILE"

    echo "Command: $CMD" | tee -a "$LOGFILE"


    if [ "$DRY_RUN" = true ]; then

        echo "DRY RUN: Not executing (just printing)" | tee -a "$LOGFILE"

    else

        echo "Executing..." | tee -a "$LOGFILE"

        $psql -c "$CMD" >> "$LOGFILE" 2>&1

        echo "Done." | tee -a "$LOGFILE"

        sleep 30

    fi

done


echo "===== REINDEX CONCURRENTLY COMPLETED: $(date) =====" | tee -a "$LOGFILE"

echo "Log file: $LOGFILE"


Sunday, July 22, 2018

Script to find archivelog generation per hour

set pagesize 120;
set linesize 200;
col day for a8;
spool archivelog.lst
PROMPT Archive log distribution per hours on each day …
  
select
  to_char(first_time,’YY-MM-DD’) day,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’00’,1,0)),’999′) “00”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’01’,1,0)),’999′) “01”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’02’,1,0)),’999′) “02”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’03’,1,0)),’999′) “03”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’04’,1,0)),’999′) “04”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’05’,1,0)),’999′) “05”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’06’,1,0)),’999′) “06”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’07’,1,0)),’999′) “07”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’08’,1,0)),’999′) “08”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’09’,1,0)),’999′) “09”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’10’,1,0)),’999′) “10”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’11’,1,0)),’999′) “11”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’12’,1,0)),’999′) “12”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’13’,1,0)),’999′) “13”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’14’,1,0)),’999′) “14”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’15’,1,0)),’999′) “15”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’16’,1,0)),’999′) “16”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’17’,1,0)),’999′) “17”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’18’,1,0)),’999′) “18”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’19’,1,0)),’999′) “19”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’20’,1,0)),’999′) “20”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’21’,1,0)),’999′) “21”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’22’,1,0)),’999′) “22”,
  to_char(sum(decode(substr(to_char(first_time,’HH24′),1,2),’23’,1,0)),’999′) “23”,
  COUNT(*) TOT
from v$log_history
group by to_char(first_time,’YY-MM-DD’)
order by day ;

Script to identify segments generating redologs

SELECT to_char(begin_interval_time,’YY-MM-DD HH24′) snap_time, 
        dhso.object_name, 
        sum(db_block_changes_delta) BLOCK_CHANGED 
  FROM dba_hist_seg_stat dhss, 
       dba_hist_seg_stat_obj dhso, 
       dba_hist_snapshot dhs 
  WHERE dhs.snap_id = dhss.snap_id 
    AND dhs.instance_number = dhss.instance_number 
    AND dhss.obj# = dhso.obj# 
    AND dhss.dataobj# = dhso.dataobj# 
    AND begin_interval_time BETWEEN to_date(’12-02-07 12:00′,’YY-MM-DD HH24:MI’)  
                                AND to_date(’12-02-07 16:00′,’YY-MM-DD HH24:MI’) 
  GROUP BY to_char(begin_interval_time,’YY-MM-DD HH24′), 
           dhso.object_name 
  HAVING sum(db_block_changes_delta) > 0 
ORDER BY sum(db_block_changes_delta) desc ;

Script to know which SQL’s are generating redo

SELECT when, sql, SUM(sx) executions, sum (sd) rows_processed 
FROM ( 
      SELECT to_char(begin_interval_time,’YYYY_MM_DD HH24′) when, 
             dbms_lob.substr(sql_text,4000,1) sql, 
             dhss.instance_number inst_id, 
             dhss.sql_id, 
             sum(executions_delta) exec_delta, 
             sum(rows_processed_delta) rows_proc_delta 
        FROM dba_hist_sqlstat dhss, 
             dba_hist_snapshot dhs, 
             dba_hist_sqltext dhst 
        WHERE upper(dhst.sql_text) LIKE ‘%Z_PLACENO%’ 
          AND ltrim(upper(dhst.sql_text)) NOT LIKE ‘SELECT%’
          AND dhss.snap_id=dhs.snap_id 
          AND dhss.instance_Number=dhs.instance_number 
          AND dhss.sql_id = dhst.sql_id  
          AND begin_interval_time BETWEEN to_date(’12-02-07 12:00′,’YY-MM-DD HH24:MI’)  
                                      AND to_date(’12-02-07 16:00′,’YY-MM-DD HH24:MI’) 
        GROUP BY to_char(begin_interval_time,’YYYY_MM_DD HH24′), 
            dbms_lob.substr(sql_text,4000,1), 
              dhss.instance_number, 
             dhss.sql_id 
) 
group by when, sql;

Script to find PGA memory allocation to BG processes

*********************************************
PGA Memory allocation to background process
*********************************************
SELECT spid, program,
pga_max_mem max,
pga_alloc_mem alloc,
pga_used_mem used,
pga_freeable_mem free
FROM V$PROCESS
WHERE spid = 2587;

Script to find memory usage by BG processes

**************************************
Memory usage for backgroung processes
**************************************
SELECT p.program,
p.spid,
pm.category,
pm.allocated,
pm.used,
pm.max_allocated
FROM V$PROCESS p, V$PROCESS_MEMORY pm
WHERE p.pid = pm.pid
AND p.spid = 2587;

Script to show active distributed tx’s in database

***************************************
script to show active distributed tx’s
***************************************
REM distri.sql
column origin format a13
column GTXID format a35
column LSESSION format a10
column s format a1
column waiting format a15
Select /*+ ORDERED */
substr(s.ksusemnm,1,10)||’-‘|| substr(s.ksusepid,1,10) “ORIGIN”,
substr(g.K2GTITID_ORA,1,35) “GTXID”,
substr(s.indx,1,4)||’.’|| substr(s.ksuseser,1,5) “LSESSION” ,
substr(decode(bitand(ksuseidl,11),
1,’ACTIVE’,
0, decode(bitand(ksuseflg,4096),0,’INACTIVE’,’CACHED’),
2,’SNIPED’,
3,’SNIPED’, ‘KILLED’),1,1) “S”,
substr(event,1,10) “WAITING”
from x$k2gte g, x$ktcxb t, x$ksuse s, v$session_wait w
— where g.K2GTeXCB =t.ktcxbxba <= use this if running in Oracle7
where g.K2GTDXCB =t.ktcxbxba — comment out if running in Oracle8 or later
and g.K2GTDSES=t.ktcxbses
and s.addr=g.K2GTDSES
and w.sid=s.indx;

REM distri_details.sql
set headin off
select /*+ ORDERED */
‘—————————————-‘||’
Curent Time : ‘|| substr(to_char(sysdate,’dd-Mon-YYYY HH24.MI.SS’),1,22) ||’
‘||’GTXID=’||substr(g.K2GTITID_EXT,1,10) ||’
‘||’Ascii GTXID=’||g.K2GTITID_ORA ||’
‘||’Branch= ‘||g.K2GTIBID ||’
Client Process ID is ‘|| substr(s.ksusepid,1,10)||’
running in machine : ‘||substr(s.ksusemnm,1,80)||’
Local TX Id =’||substr(t.KXIDUSN||’.’||t.kXIDSLT||’.’||t.kXIDSQN,1,10) ||’
Local Session SID.SERIAL =’||substr(s.indx,1,4)||’.’|| s.ksuseser ||’
is : ‘||decode(bitand(ksuseidl,11),1,’ACTIVE’,0,
decode(bitand(ksuseflg,4096),0,’INACTIVE’,’CACHED’),
2,’SNIPED’,3,’SNIPED’, ‘KILLED’) ||
‘ and ‘|| substr(STATE,1,9)||
‘ since ‘|| to_char(SECONDS_IN_WAIT,’9999′)||’ seconds’ ||’
Wait Event is :’||’
‘|| substr(event,1,30)||’ ‘||p1text||’=’||p1
||’,’||p2text||’=’||p2
||’,’||p3text||’=’||p3 ||’
Waited ‘||to_char(SEQ#,’99999′)||’ times ‘||’
Server for this session:’ ||decode(s.ksspatyp,1,’Dedicated Server’,
2,’Shared Server’,3,
‘PSE’,’None’) “Server”
from x$k2gte g, x$ktcxb t, x$ksuse s, v$session_wait w
— where g.K2GTeXCB =t.ktcxbxba <= use this if running Oracle7
where g.K2GTDXCB =t.ktcxbxba — comment out if running Oracle8 or later
and g.K2GTDSES=t.ktcxbses
and s.addr=g.K2GTDSES
and w.sid=s.indx;
set headin on
— end script

Query to find Active SQL’s in database

set feedback off
set serveroutput on size 9999
column username format a20
column sql_text format a55 word_wrapped
begin
for x in
(select username||'(‘||sid||’,’||serial#||’) ospid = ‘|| process ||
‘ program = ‘ || program username,
to_char(LOGON_TIME,’ Day HH24:MI’) logon_time,
to_char(sysdate,’ Day HH24:MI’) current_time,
sql_address,
sql_hash_value
from v$session
where status = ‘ACTIVE’
and rawtohex(sql_address) <> ’00’
and username is not null ) loop
for y in (select sql_text
from v$sqlarea
where address = x.sql_address ) loop
if ( y.sql_text not like ‘%listener.get_cmd%’ and
y.sql_text not like ‘%RAWTOHEX(SQL_ADDRESS)%’ ) then
dbms_output.put_line( ‘——————–‘ );
dbms_output.put_line( x.username );
dbms_output.put_line( x.logon_time || ‘ ‘ || x.current_time || ‘ SQL#=’ || x.sql_hash_value);
dbms_output.put_line( substr( y.sql_text, 1, 250 ) );
end if;
end loop;
end loop;
end;


/

Script to find redo generated by current sessions

#################################################
redo generated by current sessions
#################################################
select v$session.sid, username, value redo_size
from v$sesstat, v$statname, v$session
where v$sesstat.STATISTIC# = v$statname.STATISTIC#
and v$session.sid = v$sesstat.sid
and name = ‘redo size’
and value > 0
and username is not null
order by value
/

Script for trimming alert log to 1 day and taking backup of prev day



#!/usr/bin/ksh

############################################################################
##  Program :   save_alert_log.sh                                          #
##                                                                         #
##  Purpose :   The alert logs on many Oracle databases can grow to a very #
##              large size over time.  This can often impede the maintenace#
##              of the system – because the DBA will need to sometimes scan#
##              through many days or months of data when researching an    #
##              issue.  This script tries to avoid that by ensuring that   #
##              the log file can be “refreshed” on a daily basis, meaning  #
##              that only the current day’s data will be kept in the log,  #
##              while the previous day’s data will be saved to another file#
##              in a backup area.                                          #
##                                                                         #
##              This script should be run from Oracle’s crontab at midnight#
##              every night, so that the database will always have a new   #
##              alert log file each day.  An example crontab entry could be#
##              0 00 * * * /oracle/product/local/scripts/save_alert.sh 2>&1#
##                                                                         #
##  Date    :   19 May 2006.                                               #
##  Author  :   Basil S. Mullings                                          #
############################################################################
##  Modified:                                                              #
##                                                                         #
##                                                                         #
#  Modification History:                                                   #
#  DATE       WHO      DESC                                                #
#  ——–   —–    —————————————————-#
#  05/29/06   Basil    Add an extra variable LOG_KEEP_DAYS to hold the     #
#                      number of days that the log files should be kept on #
##                     the server before being deleted.                    #
##                                                                         #
##                                                                         #
############################################################################

  ##Setup some needed variables.
BKUP=bkup   ##The backup directory to store the logs…
ORATAB=”/etc/oratab”
LOG_KEEP_DAYS=365   ##Keep this many days of log files on the server.
TMPFILE=/var/tmp/OracleAlertLog   ##Just a temp scratch work area.
SQLUSER=”/ as sysdba”
GEN_ORA_ERROR=”ORA\-[0-9][0-9]*”
PATH=”$HOME:$HOME/bin:/usr/contrib/bin:/usr/local/bin:/usr/bin:/bin:/etc:.”
export PATH

  ## Now, parse the oratab file for all databases on the system.
  ## Then use the ORACLE_SID that is found in the oratab file
  ## to log onto that database, and retrieve the directory where
  ## the alter log file is stored (.ie. retrieve the path to the
  ## bdump directory.
  ##
#for sidEntry in `cat $ORATAB | grep -v “^#”`
for sidEntry in `cat $ORATAB | awk -F: ‘{print $1}’ | grep -v “^#”`
do
       ## Get date and time
    CURR_DATE=`date ‘+%a_%m%d%H%M’`    ##Example Fri_05191256   for Friday May 19th @1256 PM.

    #ORACLE_SID=`echo  $sidEntry | cut -f 1 -d :`
    ORACLE_SID=$sidEntry
    echo “Oracle Sid is $ORACLE_SID”
                                                                                        
    export ORACLE_SID                                                                   
       ## Set the Oracle environment for this SID.                                      
    ORAENV_ASK=NO                                                                     
    . /usr/local/bin/oraenv                                                             
    rm -f $TMPFILE > /dev/null 2>&1

       ##Now, let’s log onto the DB, and try to
       ##retrieve the bdump directory path.
    sqlplus -s /nolog << EOF > $TMPFILE
    connect $SQLUSER
    set heading off;
    set echo off;
    set feedback off;

    select ‘BACKGROUND_DUMP_DEST=’ ||value
    from   v\$parameter
    where  name=’background_dump_dest’;
    exit;
EOF

       ##Ok, we had a problem talking to the database.
    if [ `grep -c $GEN_ORA_ERROR $TMPFILE` -ne 0 ]
    then
         echo “ERROR: Unable to find the path to the alert log for DB $ORACLE_SID”
         rm -f $TMPFILE > /dev/null 2>&1

    else  ##Ok, we can log into the DB, now let’s go find our bdump directory.
      
         bdump=`grep BACKGROUND_DUMP_DEST $TMPFILE | awk -F “=” ‘{print $2}’`
         #echo “BDUMP is $bdump”
         bkupDir=$bdump/$BKUP

            ##Make sure our backup directory exists.
         if [ ! -d $bkupDir ]
         then
               mkdir $bkupDir  > /dev/null 2>&1
         fi

           ##Now, move the alert log.                                                 
         #echo “now moving $bdump/alert_${ORACLE_SID}.log to $bkupDir/alert_${ORACLE_SID}.$CURR_DATE”
         mv $bdump/alert_${ORACLE_SID}.log  $bkupDir/alert_${ORACLE_SID}.$CURR_DATE
       
             #Procedure to shrink the log to 365 days
             ##Keep only the last 365 days worth of logs…delete all logs older than 365 days.
         #echo “Now shrinking the logs in dir $bkupDir …”
         find $bkupDir  -name “*.*” -mtime +${LOG_KEEP_DAYS} -exec rm -f {} \;
    fi

done

Script to check space for one mount point

##########################################
SPACE CHECK FOR A MOUNT POINT IN UNIX BOX
###########################################
#!/bin/ksh
lis=`df -k /d801/oracle/SDSS | grep % | awk ‘{print $5}’| sed ‘s/%//g’`
ci=80
SCRIPT_DIR=/d002/oracle/SDSS/utilitys/
CTIME=`date +%HH%MM%SS`
if test $lis -gt $ci
then
( echo “$lis% space is used in /d801/oracle/SDSS/” > /d002/oracle/SDSS/utilitys/spacecheck.txt
mailx -s “Archive Destination > 80% in /d801/oracle/SDSS/!!” dba_ora_offshore@bp.com 919949520316@airtelap.com < /d002/oracle/
SDSS/utilitys/spacecheck.txt
)
fi
Note : The above script is only for one mount point

Script to check mount point space and get email

######################################
SCRIPT FOR CHECKING DISK SPACE IN UNIX
######################################
 #!/bin/ksh
#rm /tmp/dfk.txt
#echo “df -k output for `date` `uname -n`” > /tmp/dfk.txt
echo “File system usage exceeded the threshold on `uname -n` server- `date`” > /tmp/dfk.txt
echo “” >> /tmp/dfk.txt
i=1
while [ $i -le `df -k | grep -v proc | grep -v capacity | wc -l` ] ;do
if [ `df -k | grep -v proc | grep -v capacity | head -n $i | tail -1 | awk ‘{print $5}’ | \
sed -e ‘s/%//’` -gt 97 ] ; then
#echo “File system usage exceeded the threshold on `uname -n` server- `date`” > /tmp/dfk.txt
#echo “” >> /tmp/dfk.txt
df -k | grep -v proc | grep -v capacity | head -n $i | tail -1 >> /tmp/dfk.txt
fi
((i=i+1))
done
if [ `cat /tmp/dfk.txt | wc -l` -gt 2 ] ; then
cat /tmp/dfk.txt | mailx -s “File system full alert” bp_hostsupport@satyam.com,dba_ora_offshore@satyam.com
#cat /tmp/dfk.txt
else
exit
fi
Note: the above script will check for mount point space and will send an alert if the used space is > 97%

Script for tablespace free space email alert

#####################################################################################
MONITOR SCRIPT – it will monitor objects close to max extents, tablespace free space
#####################################################################################
#! /bin/sh
TS=`date “+%y%m%d”`
ORACLE_HOME=/d001/oracle/9.2.0.8-64
LD_LIBRARY_PATH=$ORACLE_HOME/lib
ORACLE_TERM=vt100
ORACLE_SID=ORVIT8QA
LOG=/d002/oracle/$ORACLE_SID/utilitys
PATH=/$ORACLE_HOME/bin:$PATH
export ORACLE_HOME ORACLE_SID ORACLE_TERM PATH LOG LD_LIBRARY_PATH
for n in 1
do
if [ $n -eq 1 ]; then
TWO_TASK=brcvita8_ORVIT8QA
DB_NAME=ORVIT8QA
fi
export TWO_TASK
monitor_file=$LOG/$DB_NAME.log
#n=`expr $n + 1`
 rm $monitor_file
echo “Objects close to max extents:” >> $monitor_file
sqlplus -s system/systemorvit8QA << eof >> $monitor_file
set pagesize 100;
set linesize 80;
column segment_name format a35;
column type format a10;
column owner format a10;
column extents format 9999;
column max_extents format 9999;
select owner, segment_name, segment_type “TYPE”, extents, max_extents
from sys.dba_segments
where extents/greatest(max_extents,1) >= 0.90
and segment_type not in(‘CACHE’,’ROLLBACK’);
exit;
eof
 echo “Objects that cannot get next extent:” >> $monitor_file
sqlplus -s system/systemorvit8QA << eof >> $monitor_file
set pagesize 100;
set linesize 80;
column segment_name format a33;
column type format a8;
column owner format a10;
column tablespace format a13;
column next_extent format 999999999;
select owner, segment_name, segment_type “TYPE”,
tablespace_name “TABLESPACE”, next_extent
from sys.dba_segments b
where segment_type !=’ROLLBACK’ and
next_extent > (select max(bytes) from sys.dba_free_space a
where a.tablespace_name = b.tablespace_name);
exit;
eof
 echo “Tablespaces with low freespace (< 20% & < 250 MB):” >> $monitor_file
sqlplus -s system/systemorvit8QA << eof >> $monitor_file
set echo off
set pagesize 30
set feedback off;
drop table system.mon_smt_ts;
create table system.mon_smt_ts as
(select x.tablespace_name, round(sum(x.bytes)/1048576,1) freespace
from sys.dba_free_space x
group by x.tablespace_name);
 drop table system.mon_smt_ts1;
create table system.mon_smt_ts1 as
(select tablespace_name, round(sum(bytes)/1048576,1) availspace
from sys.dba_data_files
group by tablespace_name);
set feedback on;
column “Table Space” format a20
column “Allocated” format a12
column “Free Space” format a12
column “Space Used” format a12
select x.tablespace_name “Table Space”,
to_char(availspace,’99999.9′)||’ Meg’ “Allocated”,
to_char(freespace,’99999.9′)||’ Meg’ “Free Space”,
round(freespace/availspace*100) “Pct Free”,
to_char((availspace-freespace),’99999.9′)||’ Meg’ “Space Used”
from system.mon_smt_ts x, system.mon_smt_ts1 y
where y.tablespace_name = x.tablespace_name
and round(freespace/availspace*100) < 20 and freespace<250
order by round(freespace/availspace*100);
exit;
eof
 null_findings=`egrep “no rows selected” $monitor_file | wc -l`
null_findings=`echo $null_findings`
 if [ “$null_findings” != 3 ]; then
/usr/bin/mailx -s “$DB_NAME Exception Report” dba_ora_offshore@bp.com < $monitor_file
fi
 done