Wednesday, December 19, 2012

OS ws


        ===================================
        WorkSheets - Operating System
        ===================================
http://www.athirathram.org/home.html
Linux Commands -http://www.pixelbeat.org/cmdline.html

Grepping multiple processes  - ps -ef | egrep -i "|"
spliting a file in to several  - split -b 1024m
parts of 1 GB filesize each.

Presentation Pictures   - http://www.istockphoto.com/file_search.php?action=file&lightboxID=664079
Report format-
 ###begin_report###
 
 ###end_report###

"DB - 8*5 check"
To direct an output to screen as well as file - ./102_relocate_containers.sh  | tee 102_relocate_containers.log
pk7xap01@s96ss0d14:/home/pk7xap01 : while true
> do
> db2 list utilities show detail
> sleep 60
> done
------------------------------------------------
CISM database checking procedure -
Server    - s96ars10-v2
Database  - arsprd
PORT    - 1522
Check Listener  - ps -ef | grep -i inherit
TNS Checking - tnsping arsprd
OS user   - ora_arsprd
------------------------------------------------

Laste successful TSM backup- `db2adutl query full db $LOGNAME|grep '1 Time:'|awk '{print $3}'|head -1`
To find the TSM using - dsmc q sess

Operating System
================
 Creating log file for a .sh script:
 -----------------------------------
 .sh | tee -a .log
 Send a message (Banner) for all users:
 --------------------------------------
 wall + + + + CTRL-D

 Create a link
 =============
  Soft link -
   ln -s
   Example:

    ln -s /epeople/onredom/hrepgll9 hrepprd9
   Removal of link-
    rm hrepprd9

 Process tree structure
 ======================
  SUN - pstree
  AIX - proctree

 List system error message
 =========================
  SUN - errpt

 No of processors
 ================
  AIX - lsdev -Cc processor | wc -l
  SUN - prtdiag -v
 Bit version
 ===========

  Sun  - isainfo -kv
  AIX  - bootinfo -K
  HP   - getconf KERNEL_BITS
  Linux - getconf LONG_BIT

 Memory tracking
 ===============

  Linux:
  ------
  Linux stores memory related information in a file called /proc/meminfo.
  You can list the meminfo file to see the current state of system memory.

   cat /proc/meminfo

  The Linux free command extracts and formats pertinent
  information from the meminfo file and displays it as follows:

   free -k or free -m

  To check memory size in Linux using dmesg, run the following command:

   dmesg |grep -i memory (Running dmesg command in Linux displays memory in kilobytes)


  Linux also comes with top command, top can be run to check real memory size  and
  memory utilization.Top display total memory size,used memory,free memory ,memory
  buffers size and swap memory utilization :

   top


  Solaris:
  --------
  To display the amount of RAM:
   top
   /usr/sbin/prtconf | grep Memory

   vmstat


  HP-UX:
  ------
   vmstat

   swapinfo -tm (HP-Ux swap space monitor)

  AIX:
  ----

   nmon

   lsps -s (AIX paging monitor)

   prtconf | grep -i mem

 How to check system error messages
 ==================================
  Sun - cat /var/adm/messages (Optionally tail /var/adm/messages)
  AIX - errpt

 Create and maintain screen
 ==========================
 Create screen  - screen -S
        Eg: screen -S TT11320203_Ora_task
 Attach to screen - screen -r  
      Eg: screen -r TT11320203_Ora_task
 Detach from screen - CTRL+A and release hand then press D

 Database list in EDC
 ====================

  read db_name;cat /sysadm/utils/ora_util.sid..| grep -i $db_name
  read db_name;cat ora_util.sid..| grep -i $db_name
  cat /sysadm/utils/ora_util.sid..| grep -i

 Find
 ====

  To find the pattern and print the line + the line above
  -------------------------------------------------------

  awk '{if ($2=="ALTER") {print ab,"\n",$0} {ab=$0}}'
  To find the pattern in a file
  -----------------------------
  awk '{print $1}' imp_ttu2_METADATA_ONLY_19022010.log|grep -i ORA-|head
  awk '{print $1}' imp_ttu2_METADATA_ONLY_19022010.log|grep -i ORA-|sort -u

 Loop to monitor
 ===============

  while :;do ls -l | wc -l;sleep 60;done   # use CTRL+C for exit from loop
  while : ; do ls -l *.Z | wc -l ; sleep 60 ; done

  Loop to monitor a FS
  --------------------
   cat > fschk.sh
   clear; echo 'Please enter FS: '; read fs; clear; echo 'Please enter freequency (in seconds): '; read freeq; while : ; do clear; df -h $fs ; sleep $freeq; clear ; done
   chmod 755 fschk.sh
   alias watch=./fschk.sh
  Ex:
   while : ; do clear ; echo "Fleetboard Restoration Progress (in last 30 mins)" ; ./fleetboard_db_restore_status.sh|grep "Completed Work"; sleep 1800 ; clear ; done

  To make the desired date format
  -------------------------------
  Date format: $(date +"%d%m%Y")    - ddmmyy
  Date format: $(date +"%d-%m-%Y %H:%M:%S")  - dd-mm-yyyy hh24:mi:ss


 File management
 ===============

  Replacement command
  -------------------
   Press SHIFT+: then type 1,$s/10.2.0/10.2.0.4/g -- Here 10.2.0 is the string to be replaced with 10.2.0.4
  Checking difference in 2 files
  ------------------------------
   diff

   Example:
   --------
   vkvxap01@s96gbs01:/home/vkvxap01 : ls -ltr backup_dbm_cfg_270309.txt
   -rw-r--r--   1 vkvxap01 vkvxap01       5220 Mar 27 05:05 backup_dbm_cfg_270309.txt
   vkvxap01@s96gbs01:/home/vkvxap01 : db2 get dbm cfg > dbm_cfg_updated_270309.txt
   vkvxap01@s96gbs01:/home/vkvxap01 : ls -ltr dbm_cfg_updated_270309.txt
   -rw-r--r--   1 vkvxap01 vkvxap01       5220 Mar 27 05:37 dbm_cfg_updated_270309.txt
   vkvxap01@s96gbs01:/home/vkvxap01 :
   vkvxap01@s96gbs01:/home/vkvxap01 :
   vkvxap01@s96gbs01:/home/vkvxap01 : diff backup_dbm_cfg_270309.txt dbm_cfg_updated_270309.txt
   8c8
   <  CPU speed (millisec/instruction)             (CPUSPEED) = 5.038339e-07
   ---
   >  CPU speed (millisec/instruction)             (CPUSPEED) = 5.668131e-07
   vkvxap01@s96gbs01:/home/vkvxap01 :
      

  Delete audit files
  ------------------
   find -name '*.aud' -exec rm {} \;

  Pack/ Compress
  --------------
   gzip -9
   nohup gzip -c > &
   compress

   Example:
    gzip -9 < /log/oracle/network/listener.log > /log/oracle/network/listener.log.gz
    compress < /log/oracle/network/listener.log > /log/oracle/network/listener.log.Z

  Pack/ Compress perticular files
  -------------------------------
   cd
   FILES="`ls`"
   tar -cvf .tar $FILES
   gzip --best .tar
   rm $FILES

   Example:
    cd /db2/backup_zujxap03/
    FILES="`echo ls *.trc`"
    tar -cvf db_oft1_trcs_301109.tar $FILES
    gzip --best db_oft1_trcs_301109.tar
    rm $FILES
   New Methode:


echo '';echo 'listing files to be archived:';echo '';FILES="`ls *.Z *.1`";echo $FILES;echo '';echo 'compressing..';echo '';tar -cvf logs_$(date +"%d%m%Y").tar $FILES;gzip -9 logs*.tar;echo '';echo 'files compressed as -';echo '';ls -ltr logs*tar*.gz
dsmc arch  "logs*tar*.gz"
dsmc q arch  "logs*tar*.gz"
rm $FILES

  Truncate  file
  --------------
   cat '' >
   Eg: cat '' > /log/oracle/network/listener.log

   Note:
    While handlying with listener, do not  remove this file as the listener  keeps a
    filehandle to this file.  In case , if  we accidently removed listener.log,  The
    only solution to this problem is restarting the listener. If one knows that  the
    database is at that moment not under heavy connect/disconnect-load, then restart
    online. su - -c "lsnrctl stop; lsnrctl start"
    Now the disc-space should have been freed! 


  File system HWM
  ---------------

   df -g
   read fs;df -h fs
   read dir_name;cat /sysadm/utils/ora_fsmon.`hostname`.par | grep -i $dir_name
   cat /sysadm/utils/ora_fsmon.`hostname`.par | grep -i
   cat  /sysadm/utils/ora_fsmon.`hostname`.par
   

  Finding a word in all files under a FS
  --------------------------------------
   grep $(find .)
    Ex: grep DATABASE_PASSWORD $(find .)

  Finding file sizes in unix mountpoints
  --------------------------------------

   find -xdev -type f -size +10000000c -exec du -sk {} \;|sort -nr|more

  Easly copy file from local desktop to PUTTY
  -------------------------------------------
  Copy from file (Press CTRL+A and CTRL+C )

  in PUTTY -
   cat >
   Right click the mouse
   Press CTRL+D 


  Split file into equal size
  --------------------------
  split -b m
  Once split complete, rename the files



  Eg:
   split -b 1945m VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001.gz -- spliting file into 1.9G approx

   root@s96ivk2d1:/mig12 : ls -ltr
   total 66228304
   drwxrwxrwx    2 root     system         4096 Sep 23 14:48 .snapshot
   -rw-r-----    1 vl6xaq01 vl6xaq01 16921180833 Oct 19 14:40 VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001.gz
   -rw-------    1 vl6xaq01 vl6xaq01          0 Oct 19 15:00 nohup.out
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:03 xaa
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:05 xab
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:06 xac
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:08 xad
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:09 xae
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:11 xaf
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:13 xag
   -rw-r--r--    1 root     system   2039480320 Oct 19 20:14 xah
   -rw-r--r--    1 root     system    605338273 Oct 19 20:15 xai
   root@s96ivk2d1:/mig12 :
   root@s96ivk2d1:/mig12 :
   root@s96ivk2d1:/mig12 : mv xaa VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_01
   root@s96ivk2d1:/mig12 : mv xab VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_02
   root@s96ivk2d1:/mig12 : mv xac VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_03
   root@s96ivk2d1:/mig12 : mv xad VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_04
   root@s96ivk2d1:/mig12 : mv xae VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_05
   root@s96ivk2d1:/mig12 : mv xaf VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_06
   root@s96ivk2d1:/mig12 : mv xag VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_07
   root@s96ivk2d1:/mig12 : mv xah VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_08
   root@s96ivk2d1:/mig12 : mv xai VL6XAQ01.0.vl6xaq01.NODE0000.CATN0000.20101019132228.001_09

 To find pool serevr
 ===================

  tail -100 /sysadm/utils/ora_omnib.log | grep -i dyn


 To check the total backup for a server
 ======================================
  root@:/sysadm/utils : ora_omnib -l -N | head

 TSM Commands
 ============
  Archieve to TSM  -  dsmc arch
      Eg : dsmc arch ZU8XAP01.0.zu8xap01.NODE0000.CATN0000.20081026194320.001
  
  Query TSM   -  dsmc q arch
      Eg : dsmc q arch ZU8XAP01.0.zu8xap01.NODE0000.CATN0000.20081026194320.001


  If those commands not working -


  Archieve to TSM  -  dsmc back
      Eg: dsmc back  listener.log.01042009.Z


  Query TSM   - dsmc q back
      Eg: dsmc q back  listener.log.01042009.Z

  Archive multiple files  -  dsmc archive "*"
      Eg: dsmc archive "nncc*"

  Query TSM   -  dsmc q archive "*"
      Eg: dsmc q archive "nncc*" 

  dsmc ret  "*S006297*"  -subdir=yes /db2/tmp_logs/

  Archive files under a directory
  -------------------------------
  dsmc arch -subdir=yes "/oracle/data1/exports/TT9416776/*" -desc=TT0011119940

  dsmc q arch "/oracle/data1/exports/TT9416776/*" -desc=TT0011119940

 RMAN backup schedule monitoring
 ===============================
  As root - ps -ef | grep dsm

    Eg:
     root@s96hrd11:/root : ps -ef | grep dsm
         root 1269888       1   0   Jun 24      -  0:02 /usr/bin/dsmcad -optfile=/usr/bin/dsm_s96hrd11_leadsnt.opt
         root 1274016       1   0   Jun 24      -  0:02 /usr/bin/dsmcad -optfile=/usr/bin/dsm_s96hrd11_leadt.opt
         root 1286228       1   0   Jun 24      -  0:02 /usr/bin/dsmcad -optfile=/usr/bin/dsm_s96hrd11_omr1.opt
         root 1310858       1   0   Jun 24      -  0:02 /usr/bin/dsmcad -optfile=/usr/bin/dsm_s96hrd11_epwtint.opt
         root 1327244       1   0   Jun 24      -  0:02 /usr/bin/dsmcad -optfile=/usr/bin/dsm_s96hrd11_hrapp03i.opt
         root 1331340       1   0   Jun 24      -  0:02 /usr/bin/dsmcad -optfile=/usr/bin/dsm_s96hrd11_hrapp01t.opt
         root 1335438       1   0   Jun 24      -  0:02 /usr/bin/dsmcad -optfile=/usr/bin/dsm_s96hrd11_hrapp01i.opt
         root 9347194 9789580  38 03:18:50      -  0:47 /opt/tivoli/tsm/client/ba/bin/dsmc incremental -subdir=yes / /epeople/cntrl1/ /epeople/cntrl2/ /epeople/cntrl3/ /epeople/databases/ /epeople/log/ /epeople/offredo/ /epeople/onredom/ /epeople/onredop/ /epeople/sort/ /glockware/ /home/ /opt/ /oracle/ /root/ /sysmgmt/ /tmp/ /usr/ /var/
         root 9482396 9797792   0 03:29:34  pts/1  0:00 grep dsm



    dsmc q sched <-optfile>

    Eg:
     root@s96hrd11:/root : dsmc q sched -optfile=/usr/bin/dsm_s96hrd11_epwtint.opt
     IBM Tivoli Storage Manager
     Command Line Backup/Archive Client Interface
       Client Version 5, Release 3, Level 4.0
       Client date/time: 06/27/09   03:29:45
     (c) Copyright by IBM Corporation and other(s) 1990, 2006. All Rights Reserved.

     Node Name: S96HRD11_EPWTINT
     Session established with server S96TSM02: AIX-RS/6000
       Server Version 5, Release 5, Level 1.1
       Server date/time: 06/27/09   03:29:45  Last access: 06/27/09   03:29:01

         Schedule Name: ONLINE_EPWTINT
           Description: schedules RMAN Onlinebackup
        Schedule Style: Enhanced
                Action: Command
               Options:
               Objects: /usr/bin/su - ora9i -c "export ORACLE_SID=epwtint;/usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh -l full -s BUOn -r 1 -o 30"
              Priority: 5
        Next Execution: 1 Minute
              Duration: 1 Hour
                Period:
           Day of Week: Tuesday, Saturday
                 Month: Any
          Day of Month: Any
         Week of Month: Any
                Expire: Never

    ps -ef | grep /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh

    Eg:
     root@s96hrd11:/root : ps -ef | grep /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh
        ora9i 9212104 9367796   0 03:30:06      -  0:00 /usr/bin/ksh /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh -l full -s BUOn -r 1 -o 30
         root 9416958 9797792   1 03:30:49  pts/1  0:00 grep /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh
       ora10g 9842854 8982722   0 03:29:07      -  0:00 /usr/bin/ksh /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh -l full -s ArchRedo -r 1
     root@s96hrd11:/root : ps -ef | grep /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh
        ora9i 9212104 9367796   0 03:30:06      -  0:00 /usr/bin/ksh /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh -l full -s BUOn -r 1 -o 30
         root 9670860 9797792   0 03:35:53  pts/1  0:00 grep /usr/tivoli/tsm/client/oracle/scripts/oracle_tdpo.ksh
     root@s96hrd11:/root :


  Check the log file-

    cd /opt/tivoli/tsm/client/oracle/logs

    ls -ltr | grep epwtint | grep dbback | tail

    Eg:
     root@s96hrd11:/opt/tivoli/tsm/client/oracle/logs : ls -ltr | grep epwtint | grep dbback | tail
     -rw-r--r--    1 ora9i    dba           19131 May 30 11:23 rman_out.30.05.09-03:30:06.dbbackup.epwtint.5562582
     -rw-r--r--    1 ora9i    dba           19131 Jun 02 17:09 rman_out.02.06.09-03:30:11.dbbackup.epwtint.4710402
     -rw-r--r--    1 ora9i    dba           19131 Jun 06 11:13 rman_out.06.06.09-03:30:09.dbbackup.epwtint.7864520
     -rw-r--r--    1 ora9i    dba           19131 Jun 09 17:33 rman_out.09.06.09-03:30:16.dbbackup.epwtint.8315070
     -rw-r--r--    1 ora9i    dba           19131 Jun 13 11:27 rman_out.13.06.09-03:30:04.dbbackup.epwtint.8839226
     -rw-r--r--    1 ora9i    dba            6093 Jun 16 03:30 rman_out.16.06.09-03:30:10.dbbackup.epwtint.8265896
     -rw-r--r--    1 root     system          489 Jun 16 19:57 rman_out.16.06.09-15:06:52.dbbackup.epwtint.8212650
     -rw-r--r--    1 ora9i    dba            6111 Jun 17 16:13 rman_out.17.06.09-15:36:31.dbbackup.epwtint.9240606
     -rw-r--r--    1 ora9i    dba           19131 Jun 23 19:36 rman_out.23.06.09-08:00:14.dbbackup.epwtint.4481260
     -rw-r--r--    1 ora9i    dba            5456 Jun 27 03:30 rman_out.27.06.09-03:30:06.dbbackup.epwtint.9212104
    tail -f

    Eg:
     root@s96hrd11:/opt/tivoli/tsm/client/oracle/logs : :30:06.dbbackup.epwtint.9212104                        <
     RMAN-08522: input datafile fno=00079 name=/epeople/databases/epwtint/dbf/pclarge01.dbf
     RMAN-08522: input datafile fno=00103 name=/epeople/databases/epwtint/dbf/pswork01.dbf
     RMAN-08522: input datafile fno=00126 name=/epeople/databases/epwtint/dbf/tllarge01.dbf
     RMAN-08522: input datafile fno=00045 name=/epeople/databases/epwtint/dbf/eotpapp01.dbf
     RMAN-08522: input datafile fno=00025 name=/epeople/databases/epwtint/dbf/eocmwrk01.dbf
     RMAN-08522: input datafile fno=00029 name=/epeople/databases/epwtint/dbf/eodslrg01.dbf
     RMAN-08522: input datafile fno=00034 name=/epeople/databases/epwtint/dbf/eoeilrg01.dbf
     RMAN-08522: input datafile fno=00039 name=/epeople/databases/epwtint/dbf/eoiulrg01.dbf
     RMAN-08522: input datafile fno=00052 name=/epeople/databases/epwtint/dbf/glapp01.dbf
     RMAN-08038: channel epwtint_t1: starting piece 1 at 27-jun-2009_03:30:13
   

 Copy directory
 ==============
  cp -r
  tar cf - ./ | ( cd ; tar xf - )

  Example:
   tar cf - ./V9.1 | ( cd /mif/DB/mifarchive/AbsBackup/20090325to20190325/DB2/s96mif0c0 ; tar xf - )


 Compress directory
 ==================

  tar -cvf .tar   
  Example: tar -cvf pk6xap01_db2move.tar db2move

xxx -------------------------------------------------------------------- xxx -------------------------------------------------------------------- xxx

Linux Shell Scripting Excercises
================================

Sites:  http://www.freeos.com/guides/lsst/
 http://linuxgazette.net/133/cherian.html
Eg :1
-----
 hostname>name.log ; vserver=`cat name.log` ; echo $vserver ; rm name.log
Eg :2
-----
 ora1023@s96dbt01:/home/ora1023 : cat test.sh
 echo "Enter character:"
 read vchr
 if [ "$vchr" = "" ]
 then
    echo 'Invalid!'
 else
    echo $vchr
 fi

Eg :3
-----
 uname > OSname.log
 vos=`cat OSname.log`
 rm OSname.log
 echo 'File removed sucessfully!'
 if [ "$vos" = "SunOS" ]
 then
  echo 'Sun Operating System'
 else
  echo 'Not a Sun Operating System'
 fi

xxx -------------------------------------------------------------------- xxx -------------------------------------------------------------------- xxx

root@s96iuk0d0:/oracle/log/iukp/cdump : cp -rf /oracle/log/iukp/cdump/core_* /root/core
root@s96iuk0d0:/oracle/log/iukp/cdump : cd /root/core
root@s96iuk0d0:/root/core : ls -l
total 18
drwxr-x---   2 root     root         512 Feb  3 23:20 core_10403
drwxr-x---   2 root     root         512 Feb  3 23:20 core_1093
drwxr-x---   2 root     root         512 Feb  3 23:20 core_1103
drwxr-x---   2 root     root         512 Feb  3 23:20 core_11675
drwxr-x---   2 root     root         512 Feb  3 23:20 core_22041
drwxr-x---   2 root     root         512 Feb  3 23:20 core_23177
drwxr-x---   2 root     root         512 Feb  3 23:20 core_27323
drwxr-x---   2 root     root         512 Feb  3 23:21 core_28608
drwxr-x---   2 root     root         512 Feb  3 23:21 core_4117
root@s96iuk0d0:/root/core :
root@s96iuk0d0:/root : tar -cvf /root/core.tar /root/core
a /root/core/ 0K
a /root/core/core_10403/ 0K
a /root/core/core_10403/core 151478K
a /root/core/core_1093/ 0K
a /root/core/core_1093/core 28160K
a /root/core/core_1103/ 0K
a /root/core/core_1103/core 5784K
a /root/core/core_11675/ 0K
a /root/core/core_22041/ 0K
a /root/core/core_22041/core 135477K
a /root/core/core_23177/ 0K
a /root/core/core_23177/core 0K
a /root/core/core_27323/ 0K
a /root/core/core_27323/core 149837K
a /root/core/core_28608/ 0K
a /root/core/core_4117/ 0K
a /root/core/core_4117/core 138990K
root@s96iuk0d0:/root :
root@s96iuk0d0:/root :

root@s96iuk0d0:/oracle/log/iukp/cdump : mv /root/core.tar.gz .
root@s96iuk0d0:/oracle/log/iukp/cdump : bdf .
Filesystem            kbytes    used   avail capacity  Mounted on
/oracle/log           985951  595769  331025    65%    /oracle/log
root@s96iuk0d0:/oracle/log/iukp/cdump :

Script to be checked -
cat /tmp/awk.scr
awk '/ORA-1109/{print x};{x=$0}' /dblogs/oft1/bdump/alert_oft1.log.1
awk '/ORA-1109/{print}' /dblogs/oft1/bdump/alert_oft1.log.1
awk '/ORA-1109/{getline;print}' /dblogs/oft1/bdump/alert_oft1.log.1

db2 WS

        ==============================
        WorkSheets - DB2 Databse
        ==============================
db2 restore database tk1xapib from /olap/TT12258603 taken at 20101008164629  with 4 buffers buffer 4096 parallelism  4 without prompting
** In IVK task- Update the script with LONG Tablespace size : 15316320

** All DB2 licence Krys are stored in - s96gsuc4:/software/DB/db2software/db2_license_keys
gb_db@s96gsuc4:/software/DB/db2software/db2_license_keys $ ls -ltr
total 16
drwxrwxrwx   2 root     sys           96 Apr 12  2007 db2v7
drwxrwxrwx   2 root     sys           96 May 29  2008 db2v95
drwxrwxrwx   2 root     sys           96 Oct 15  2008 db2v9
drwxrwxrwx   2 root     sys         8192 Sep 22 10:54 db2v8

In Fleetboard    - db2start;nohup db2 -tvf redirct_zu5xai02_160809.sql -l redirct_zu5xai02_160809.log &
For IBLIS Eg TT - 9637862
All possible CI Keys   - /sysmgmt/sat/base/bin/sat_ci_provider -db
For doing verify on one db  - sat_verify_db -ci s96mif8d6:fk1xat09:FK1XAT09

For  NAG/Libelle TT Eg: 10457716
Ref : DB2 process model - http://www.ibm.com/developerworks/data/library/techarticle/0304chong/0304chong.html

For running a SQL in nohup -
zuoxap01@s96vdc0d0:/cluster/vdrg00/db2home/zuoxap01/TT11519486 : cat 11519486.sh
#!/bin/ksh
db2 connect to zuoxap01;
db2 -tvf Delete_FINList2.sql -l Delete_FINList2.log;
db2 terminate;
zuoxap01@s96vdc0d0:/cluster/vdrg00/db2home/zuoxap01/TT11519486 : nohup ./11519486.sh &


For instance creation in EDC  -  Create user and group
   
   
     cd /sysmgmt/sat/db_tools/bin
     db2_create_instance -U -F -v 9.1 vkixap01

DB2 Database
============
db2 list active databases;echo '';db2 get db cfg for $DB2INSTANCE|grep -i pend;echo '';db2 get snapshot for dbm|grep -i start;echo '';tail -15 sqllib/db2dump/db2diag.log
 ==============================
1) Checking DB2 error description
 ==============================

 Check diag.log file -
  less sqllib/db2dump/db2diag.log
  tail -f sqllib/db2dump/db2diag.log
 Check the error-
  db2diag -rc
  db2 "? "


DB2 Knowledge Bank
==================
  To check startup time : db2 get snapshot for database manager|head -20
- how to
 select system time        - db2 values current timestamp
- how to
 list the instances configured in the server     - in SUN - /opt/IBM/db2/V8.1/instance : ./db2ilist
            in AIX - /usr/opt/IBM/db2/db2_08_01/instance
            in db2 prompt - db2ilist
 list the instances that are running     - ps -ef | grep -i db2
 create an instance       - ./db2icrt -u
 list the connected instance       - db2 get instance
 drop instance        - ./db2idrop -f
 start an instance       - db2start
 stop an instance       - db2stop

 find the version of db2 that the database is using   - db2level
 find the bit version of db2 that the database is using   - db2level
 find the fixpack version       - db2level

 track the memory        - db2mtrk -

 list the default database path      - db2 get dbm cfg | grep -i dbpath
 list databases created under one instance    - db2 "list db directory"
            or
            db2 "list db directory"|grep -i "database name"
 list the max number of databases activate simultaneously  - db2 "get dbm cfg" | grep -i numdb
 create database        - db2 "create database using codeset territory "
 the number of active databases under that instance   - db2 "list active databases"
 the nodes created       - db2 "list node directory"
 drop databse        - db2 "drop db "
 activate the database       - db2 "activate db "
 know if the database is active      - db2 "list active databases"
 deactivate the database       - db2 force applications all;db2 terminate;db2 deactivate db
 restart the database       - db2 "restart db "
 know if you are already connected to the database   - db2 "get connection state"
 manually archive a log file      - db2 archive log for db
 know if the database is remote or local     - db2 "list database directory"
 disconnect only one application      - db2 "force application ()"
 disconnect all applications      - db2 "force applications all"

 start the das        - db2 "start database manager"
 disconenct from the db after connecting to it    - db2 "terminate"

 update the parameter newlogpath      - db2 "update db cfg for using NEWLOGPATH "
 find log file size       - 1) db2 get db cfg for |  grep -i log
            2) (LOGFILSIZ * 4KB)/1024
 find total log file size (including primary & secondary)  - 1) db2 get db cfg for |  grep -i log
            2) ((LOGFILSIZ * 4KB)/1024)* (LOGPRIMARY + LOGSECOND)
               Eg: ((50000 * 4K)/1024)* (245+10) = 200000 (200 Mb) * 255 = 51000 (51 GB)
                            
 list dbm parameters       - db2 "get dbm cfg"
 update the dbm parameters      - db2 "update dbm cfg using "
 check what are the environment variables set    - db2set -all
 update one environment variable      - db2set = Eg: db2set db2comm=tcpip
 set the environment variable to null / reset the variable  - db2set =
 provide IBM with db information while opening a PMR   - db2support . -d $DB2INSTANCE -cl 0
 display the license information      - db2licm -l
 add a license to the product      - db2licm -a
           for listing all options go for db2licm
 find the database port       - 1) db2 get dbm cfg | grep -i svcename
            2) cat /etc/services | grep -i
 find the location of the installed product , on AIX, sun etc  - 1) issue uname -a
            2) if sun => opt/IBM/db2/V8.1
            3) if AIX => /usr/opt/IBM/db2/db2_08_01
*** what is the difference betweeen connect reset / terminate  -
 find the authoritises of the user on the database /   - query syscat.dbauth or db2 get authorizations
      on the tablespaces /     query table syscat.tbspaceauth or
        on the tables     query table syscat.tabauth
 find the authorizations for the current user    - db2 get authorizations

*** grant connection to the database     - db2 "grant connect on database to user "
 verify whether the db is in automatic memory management mode  - db2 "get db cfg for db2inst1" | grep -i memory
 grant role to a user       - db2 connect to $DB2INSTANCE user db2secad using db2secad; db2 grant role ZA2_DEVELOPER to kgampe5; db2 terminate;
 verify the granted role       - db2 connect to $DB2INSTANCE; db2 "select substr(grantee,1,15) grantee ,substr(rolename,1,15) role from syscat.roleauth where rolename='ZA2_DEVELOPER' and grantee='KGAMPE5'";db2 terminate


- how to find
 db2diag.log file        - db2 get dbm cfg  | grep -i diagpath or sqllib/db2dump/
 diag level        - db2 get dbm cfg | grep -i diaglevel
 db2inst1.nfy file       - sqllib/db2dump/
 db2eventlog.000        - sqllib/db2dump/
- how to find
 the number of applications connected to the database    - db2 "list active databases"|grep -i applications
 the tables in the database      - db2 "select count(*) cnt from syscat.tables"
 the tablespaces, and find the tablespace size of id=2, find the HWM - db2 "list tablespaces show detail"
            db2 "select pagesize from syscat.tablespaces where tbspaceid=2"
 if there is a restore/ backup or load in progress   - db2 list utilities show detail
            db2pd -utilities
 the location of the containers of the tablespaces   - db2 list tablespace containers for show detail
- how to
 find the number of configured bufferpools    - query table syscat.bufferpools
 create a bufferpool       - db2 "create bufferpool size 500 pagesize <4>k"
 drop bufferpool        - db2 "drop bufferpool "
 alter bufferpool       - db2 "alter bufferpool immediate size
 find active bufferpools       - db2 get snapshot for bufferpools on za2xai03|egrep "Bufferpool name|Current size"
 find bufferpools with pages      - db2 'select substr(BPNAME,1,15)  BPNAME,BUFFERPOOLID,PAGESIZE,BLOCKSIZE,npages from syscat.bufferpools'

 create tablespace (DMS)       - db2 "create tablespace pagesize <4k k..="k.." k="k"> managed by database using (file '/ 1000) extentsize 4 PREFETCHSIZE 8 bufferpool bp_8k"
 create tablespace (SMS)       - db2 "create tablespace pagesize <4k k..="k.." k="k"> managed by system using ('')  extentsize 8 prefetchsize 32 bufferpool bf_16k"
 alter tablespace - resize pages      - db2 "alter tablespace resize(all )" /
    - resize size      - db2 "alter tablespace resize(all )"  /
    - resize pages      - db2 "alter tablespace resize(file '' )" /
    - extend pages      - db2 "alter tablespace extend(file '' )"  /       
    - extend pages      - db2 "alter tablespace extend(all )" /
    - for simultaniously add|extend|resize containers - db2 "alter tablespace
            add (file <'file>' )
           extend (file <'file>' )
           rezize (file <'file>' )"
    - with enabling autoresize     - db2 "alter tablespace
           autoresize yes increasesize percent
           maxsize |none"
 find out what is the state of the tablespace means   - db2 "list tablespaces show detail" | grep -i state
            then issue db2tbst
            0x0000 => normal
            0x0004 => reorg pending
            0x0008 => backup pending
            ....etc...
- how to find
 tablesapce workload       - a) db2 "select TBSP_ID,TBSP_NAME,TBSP_TYPE,TBSP_TOTAL_SIZE_KB,TBSP_USABLE_SIZE_KB,TBSP_USED_SIZE_KB,TBSP_FREE_SIZE_KB,TBSP_UTILIZATION_PERCENT,TBSP_USED_PAGES,TBSP_FREE_PAGES,TBSP_PAGE_SIZE from SYSIBMADM.TBSP_UTILIZATION"

            b) db2 "select SUM(TBSP_USED_SIZE_KB)  from SYSIBMADM.TBSP_UTILIZATION"
            c) db2 "select (SUM(TBSP_USED_SIZE_KB)*100)/SUM(TBSP_TOTAL_SIZE_KB)  from SYSIBMADM.TBSP_UTILIZATION"
- how to find
 tablespaces using automatic storage/Auto-resize enabled   - db2 get snapshot for tablespaces on $DB2INSTANCE|egrep -i "Tablespace ID|Tablespace name|Using automatic storage|Auto-resize enabled"
- how to find the      
 territory of the database      - db2 get db cfg for | grep -i territory
 code set of the database      - db2 get db cfg for | grep -i code
 service name        - db2 get dbm cfg | grep -i svcename
 log file size        - db2 get db cfg for | grep -i log
 heap values        - db2 get db cfg for | grep -i heap
*** path to archive log       - db2 get db cfg for | grep -i log
*** active log         - db2 get db cfg for | grep -i log
 number of primary / secondary logs     - db2 get db cfg for | grep -i log
 how many logs are allocated when the db is started   - db2 get db cfg for | grep -i logprimary
*** if the database is in backup / restore / rollforward pending state - db2 get db cfg for | grep -i  pending
 if the database is in recovery mode     - db2 get db cfg for | grep -i recovery


- how to
 extract the DDL statements of the objects in the database  - using db2look utility
            Eg: db2look -d db2test -e -o dup_db2test.sql -l -a -xd -f -fd
            Eg: db2look -d vk0xap02 -e -tw J51RHIST -o tab_J51RHIST_data.sql -l -a -xd -f -fd
- how to
 export to an ixf file       - db2 export to of ixf "
 export a schema        - using db2move utility
 export a table        - db2 export to of ixf "select * from "
*** remove a table from check pending state     -
*** export with out using db2export tool     -
 import into a table        - db2 import from of ixf replace_create into in

- how to
*** find if the tables are in check pending state    - db2 "select substr(tabname,1,15) TABNAME,status from syscat.tables where status='C'"
*** find the time of last run runstats on the table    - db2 "select substr(tabname,1,15) TABNAME,stats_time from syscat.tables where tabname=''"

- how to
 do offline reorg on a table       - db2 reorg table index
 stop reorg on a table       - db2 reorg table inplace stop
 monitor reorg in a table      - db2pd -db -reorgs
 reorg a table and use a temp file for this reorg   - db2 reorg table use
 reorg all indexes for a table      - db2 reorg indexes all for table allow read access
 update statistics on a table      - db2 reorgchk update statistics on table
 find the last analyzed date      - db2 "select tabname,stats_time from syscat.tables where tabname='' and tabschema=''"
 runstats on a table       - db2 runstats on table allow read access
 Online reorg        - db2 "select 'REORG TABLE '||TRIM(tabschema)||'.'||tabname||' INPLACE ALLOW WRITE ACCESS;'  from syscat.tables where tabschema in (select distinct substr(tabschema,1,15)tabschema from syscat.tables where tabschema not like 'SYS%')"
 Online RUNSTAT        -
db2 "select 'RUNSTATS ON TABLE '||TRIM(tabschema)||'.'||tabname||' AND DETAILED INDEXES ALL ALLOW WRITE ACCESS;'  from syscat.tables where tabschema in (select distinct substr(tabschema,1,15)tabschema from syscat.tables where tabschema not like 'SYS%') and type='T'"

- how to check reorg stats
db2 "select REORG_START,REORG_END from sysibmadm.snaptab_reorg where tabname='FK1R_MGNTUNITFILTE'"
select rtrim(substr(table_schema,1,10)) as "Schema",rtrim(substr(table_name,1,29)) as "Table_name",
case reorg_status
  when 1 then 'Started'
  when 2 then 'Paused'
  when 3 then 'Stopped'
  when 4 then 'Completed'
  when 5 then 'Truncated'
end as status,
(minute(reorg_end - reorg_start)) as "Minutes_Ran"
from table(sysproc.snapshot_tbreorg('',-1)) as t where date (reorg_start) > (current_date - 1 day) order by reorg_start desc;
db2 "describe select * from table(snapshot_tbreorg('',0))a"
- how to find
 since when the database has been up     - db2 get snapshot for dbm | grep -i timestamp or
            db2 get snapshot for dbm | grep -i start
 detailed inforamation of the applications    - db2 list applications for db show detail
*** number of deadlocks       - db2 get snapshot for database on | grep -i lock
*** if any application is blocking another application   - db2 get snapshot for all applications | grep -i lock
          - db2 get snapshot for all applications | egrep -i "held|handle"
 No of locked tables        - db2 get snapshot for locks on $DB2INSTANCE|grep -i "Table Name" | sort -u
 No of locked tablespaces      - db2 get snapshot for locks on $DB2INSTANCE|grep -i "Tablespace Name" | sort -u
 No of locked schemas        - db2 get snapshot for locks on $DB2INSTANCE|grep -i "Table Schema" | sort -u            db2 get snapshot for application agentid "59805"


- how to
 Check the integrity of backup image     - db2ckbkp -h   
 check database size        - db2 "call get_dbsize_info(?,?,?,-1)"
 backup a database to disk      - db2 backup database online to
 check backup retention policy      - db2 get db cfg for | grep -i num_db_backups
*** backup a database to tsm      -
*** One tablespace is in backup pending state, how to remove it from  - db2 backup db tablespace online use tsm
*** backup pending state       - db2 get db cfg for | grep -i pending
*** check the backup file present in tsm     - db2adutl query full db
*** verify if the backup is not corrupted     - db2adutl verify
 verify the tablesapce info in backup      - db2adutl verify tablespaceonly taken at db
 retrive the backup image to the local FS    - db2adutl extract full taken at without prompting


- how to
 list backup history       - db2 list history backup all for db
 list archive history       - db2 list history archive log all for | tail -5
 list history of backups stored in tsm     - db2adutl query full db
*** list the history of tables that are altered    -


- how to
 recover a database to the first consistency point   - db2 rollforward db query status;
            db2 rollforward db stop;
            db2 rollforward db to ;       
            db2 rollforward db complete
 recover a database to end of logs     - db2 rollforward db to end of logs
 recover a database to a PIT      - db2 rollforward db to
 complete the recovery process      - db2 rollforward db to [|end of logs] complete
 stop the recovery process      - db2 rollforward db stop


- how to restore a database
 from a backup on disk       - db2 restore db from taken at
*** from a backup IN TSM       - db2 restore db use tsm taken at
*** with different FS structures, how would you set the target container  -
 paths


Restore a database from its own backup:
---------------------------------------
db2adutl query full db $DB2INSTANCE
db2 list history backup all for $DB2INSTANCE
db2 get db cfg for $DB2INSTANCE|grep -i "Path to"
db2 connect to $DB2INSTANCE; db2 "call get_dbsize_info(?,?,?,-1)" ; db2 terminate
db2 list active databases
db2 force applications all;db2 terminate
db2 force applications all;db2 terminate
db2stop force
db2start;nohup db2 restore db $DB2INSTANCE use tsm open 1 sessions taken at with 2 buffers buffer 1024 parallelism 1 without prompting &
tail -f nohup.out
db2 list utilities show detail
db2 rollforward db $DB2INSTANCE stop
db2 rollforward db $DB2INSTANCE to ""
db2 rollforward db $DB2INSTANCE complete
db2 get db cfg for $DB2INSTANCE |grep -i pend
db2 connect to $DB2INSTANCE;db2 terminate
db2 backup db $DB2INSTANCE tablespace syscatspace online use tsm
db2 get db cfg for $DB2INSTANCE|grep -i "Path to"
---------------------------------------


- how to check the listener status
 check service name       - db2 get dbm cfg  |grep -i svc
 check services for port number      - cat /etc/services | grep -i |grep -v DB2_
        grep "^$DB2INSTANCE" /etc/services | awk '{print $2}' | awk -F'/' '{print $1}'
 Check the port availability      - netstat -an | grep -i

 Check reorg on user defined date     - db2 "select * from table(snapshot_tbreorg('',-1)) x where date(reorg_start) = '07.06.2009'"

- how to
 drop objects in a schema       - db2 "select 'DROP '||case type when 'T' then 'TABLE ' when 'V' then 'VIEW ' end||tabschema||'.'||tabname||';' from syscat.tables where tabschema not like '%SYS%'"

- how to
 Kill a DB2 application       - db2 force application ""
 select current timestamp from dual     - db2 "SELECT CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1"
 Checking the db is whether in archive/noarchive mode   - db2 get db cfg for VKJXAP90|egrep "LOGRETAIN|USEREXIT"

- how to
 Find the backup size directly taken to TSM    - dsmc query backup "//*"
 Find the object name by object ID     - db2 "select substr(rtrim(tabschema)||'.'||rtrim(tabname),1,60) from syscat.tables where tbspaceid=12 and tableid=535"
  

-how to

 Drop deadlock event monitor      - db2 "select * from syscat.eventmonitors where EVMONNAME ='DB2DETAILDEADLOCK'"
            db2 set
            db2detaildeadlock state 0
            db2 drop event monitor db2detaildeadlock

DB Export for db2:
==================
 root / ssh / O 

 su -

 Check db size
  db2 connect to
  db2 "call get_dbsize_info(?,?,?,-1)"
  db2 terminate

 Check the space in OS level and craete one directory in the name of TT

 Go to the directory and issue-
  db2look -d -a -x -e -l -f -o db2look__.ddl
  db2move export -aw


Reorg/Runstat on database
=========================
reorg on database-
 1) db2 "select distinct TABSCHEMA from syscat.tables"
 2) db2 "select 'reorg table '||ltrim(rtrim(TABSCHEMA))||'.'||ltrim(rtrim(TABNAME))||' inplace allow write access;' from syscat.tables where TABSCHEMA='' and type='T'"
 3) db2 "select 'reorg indexes all for table '||ltrim(rtrim(TABSCHEMA))||'.'||ltrim(rtrim(TABNAME))||' allow write access;' from syscat.tables where TABSCHEMA='' and type='T'"

runstat on database-

 1) runstats on table .  and detailed indexes all allow write access;
 2) db2 "select 'runstats on table '||ltrim(rtrim(TABSCHEMA))||'.'||ltrim(rtrim(TABNAME))||' and detailed indexes all allow write access;' from syscat.tables where TABSCHEMA='' and type='T'"
 or
    db2 "runstats on table MTMCSEIN.MTMROR AND detailed INDEXES all ALLOW NO ACCESS"

 For a runstat with no access
 or

    db2 "runstats on table MTMCSEIN.MTMROR AND detailed INDEXES all ALLOW read ACCESS"

 For a runstat with read access
 --------
 Example:
 --------

 Following is an example for RUNSTAT through shell script (From IVK)
 vl6xat01@s96ivk2d0:/home/vl6xat01 : cat runstats.sh
 #!/usr/bin/ksh
 DB=$LOGNAME
 tmpf=/tmp/runstats.$$.tmp
 db2 connect to $DB
 db2 -x "select tabschema,tabname from syscat.tables where tabschema not like 'SYS%' and type='T'" > $tmpf
 cat $tmpf | while read s t
 do
   db2 -v "runstats on table $s.$t and detailed indexes all"
 done

 rm -f $tmpf

 db2 connect reset;
 ----------------------------------------------------------------------------------------
 Example script to REORG and RUNSTATS on a database other than tabschema not like 'SYS%':
 ----------------------------------------------------------------------------------------
 #!/usr/bin/ksh
 DB=$LOGNAME
 tmpe=/tmp/reorg.$$.tmp
 tmpf=/tmp/runstats.$$.tmp
 db2 connect to $DB
 db2 -x "select tabschema,tabname from syscat.tables where tabschema not like 'SYS%'" > $tmpe
 cat $tmpe | while read p q
 do
   db2 -v "reorg table $p.$q inplace allow write access"
 done
 rm -f $tmpe
 db2 -x "select tabschema,tabname from syscat.tables where tabschema not like 'SYS%' and type='T'" > $tmpf
 cat $tmpf | while read s t
 do
   db2 -v "runstats on table $s.$t and detailed indexes all allow write access"
 done
 rm -f $tmpf
 db2 connect reset;


Backup/Restore
==============
 DB2 offline backup to local directory:
 --------------------------------------
  1) mkdir
  2) chown -R :
  3) db2 force applications all;db2 force applications all
  4) db2 terminate;db2stop force
  5) db2start;db2 backup db $DB2INSTANCE to

  or

  5) db2start;nohup db2 backup db $DB2INSTANCE to compress &

  6) db2 terminate;db2 activate db $DB2INSTANCE


 DB2 online backup to local directory:
 -------------------------------------
  1) mkdir
  2) chown -R :
  3) db2start;db2 backup db $DB2INSTANCE online to

  or

  3) db2start;nohup db2 backup db $DB2INSTANCE online to compress &


 DB2 offline backup to TSM:
 --------------------------
  1) db2 force applications all;db2 deactivate database $DB2INSTANCE;db2stop force
  2) db2start;db2 backup db $DB2INSTANCE use tsm

  3) db2 list utilities show detail
  4) db2 list history backup all for database  $DB2INSTANCE | tail -30
  5) db2 terminate;db2 activate db $DB2INSTANCE
  6) db2adutl query full db $DB2INSTANCE

 DB2 online backup to TSM:
 -------------------------
  Database level backup:
  ----------------------

   1) db2 backup db $DB2INSTANCE online use tsm (We can add parallelism and buffers for a fast backup)
   2) db2 list utilities show detail
   3) db2 list history backup all for database  $DB2INSTANCE | tail -30
   4) db2adutl query full db $DB2INSTANCE

  Tablespace level backup:
  ------------------------
   1) db2 backup db $DB2INSTANCE tablespace online use tsm
   2) db2 list utilities show detail
   3) db2 list history backup all for database  $DB2INSTANCE | tail -30
 DB2 Restore:
 ------------

 db2 restore db TK0XAT01 use tsm open 1 sessions taken at 20091125230545 with 2 buffers buffer 1024 parallelism 1

 db2 rollforward db TK0XAT01 to 2009-11-26-08.50.00.000000 USING LOCAL TIME
 db2start;db2 restore db oftxat01 from /dbdumps/oftxat01 taken at 20110110072033

Shell scripting with DB2
========================


 IVK tasks -Downloading dump files
 ---------------------------------
 for i in
 do
 wget $i
 done


 Example:
 --------
 for i in https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-a https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-b      https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-c https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-d https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-e https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-f https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-g https://ivk.she2.emea.bg.corpintra.net/ivkmds/MDSDB12.0.db2inst2.NODE0000.CATN0000.20090122175058.001.gz-h
 do
 wget $i
 done

 database="ZU5XAP01"

 echo "START"
 date
 db2 connect to $dataBase
 echo "convert to large"
 time db2 "ALTER TABLESPACE USERSPACE5 CONVERT TO LARGE"
 echo "doing reorg"
 time db2 "REORG TABLE FB.TOUREVENTRECORDDATA ALLOW NO ACCESS USE TEMPSYS16K"
 echo "DONE"
 date
-------------------------------
- Multiple db restarted in DB2:
-------------------------------
for i in fk8xap01 tkaxat01 tkexap01 tkexat01 vkdxap01 vlhxae01 vlhxae02 vlhxai01 vlhxai02 vlhxap01 vlhxap02 zu1xap01 zu1xap02 zurxat01
do
echo "Database $i@`hostname`"    
echo "--------------------------"
su - $i -c "db2 list active databases;db2 get db cfg for $i|grep -i pend"
echo ''
echo '++++++++++++++++++++++++++++++++++++++++++++++++++'
echo ''
done

for i in fk8xap01 tkaxat01 tkexap01 tkexat01 vkdxap01 vlhxae01 vlhxae02 vlhxai01 vlhxai02 vlhxap01 vlhxap02 zu1xap01 zu1xap02 zurxat01
do
echo "Database $i@`hostname`"    
echo "--------------------------"
su - $i -c "db2 force applications all;db2 force applications all;db2 force applications all;db2 terminate;db2stop force;db2start;db2 terminate;db2 activate db $i;db2 list active databases;db2 get db cfg for $i|grep -i pend;db2 get snapshot for dbm|grep -i start"
echo ''
echo "Restart completed for Instance $i@`hostname`"
echo ''
echo '++++++++++++++++++++++++++++++++++++++++++++++++++'
echo ''
done


-- For checking all instance/databases memory in a server
 for i in zu8xai01 zu8xai02 zu8xai04 zu8xai05 zu8xai06
 do
 echo "Database $i@`hostname`"
 echo "----------------------------"
 su - $i -c "db2 attach to $i;db2 get dbm cfg show detail|grep -i memory;db2 connect to $i;db2 get db cfg for $i show detail|grep -i memory;db2 terminate"
 echo ''
 done

-- For checking all databases in a server
 for i in
 do
 echo ''
 echo "Database $i@`hostname`"    
 echo "----------------------------"        
 su - $i -c "db2 list active databases;db2 connect to  $i;db2 terminate"
 echo ''
 done

 Example:
 --------
 root@s96dbt01 > for i in oftxat01 db2inst1
 root@s96dbt01 > do
 root@s96dbt01 > echo ''
 root@s96dbt01 > echo "Database $i@`hostname`"
 root@s96dbt01 > echo "----------------------------"
 root@s96dbt01 > su - $i -c "db2 list active databases;db2 connect to  $i;db2 terminate"
 root@s96dbt01 > echo ''
 root@s96dbt01 > done
-- For shutdown all databases in a server
 for i in vk1xap02 vk1xap03 vk1xap04 vk1xap07 vk1xap08 vk1xap09 vk1xap10 vk1xap11 vk1xap12 vk1xap13
 do
 echo ''
 echo "Database $i@`hostname`"    
 echo "----------------------------"        
 su - $i -c "db2 list active databases"
 echo ''
 done

 for i in vk1xap02 vk1xap03 vk1xap04 vk1xap07 vk1xap08 vk1xap09 vk1xap10 vk1xap11 vk1xap12 vk1xap13
 do
 echo ''
 echo "Database $i@`hostname`"    
 echo "----------------------------"        
 su - $i -c "db2 list active databases;db2 force applications all;db2 terminate;db2 deactivate db $i;db2stop"
 echo ''
 done

-- For restarting all databases in a server

 do
 echo $i                  
 su - $i -c "db2start;db2 activate db $i"
 done
-- For checking the current active log for all dbs in a server -
 for i in vk1xap02 vk1xap03 vk1xap04 vk1xap07 vk1xap08 vk1xap09 vk1xap10 vk1xap11 vk1xap12 vk1xap13 vk1xap14
 do
 echo ''
 echo "Database $i@`hostname`"    
 echo "----------------------------"        
 su - $i -c "db2 list active databases;db2 get db cfg for $i | grep -i log | grep -i "First active log file""
 echo ''
 done
-- For collecting the current settings for all dbs in a server -
 for i in  pk6xae01 pk6xae02 pk6xae04
 do
 echo ''
 echo "Database $i@`hostname`"    
 echo "----------------------------"        
 su - $i -c "cd /db2/TT9324315/$i;db2 list db directory > db_dir.txt;db2set -all > dbset_cfg.txt"
 echo ''
 done

-- For checking Restoration status of Fleetboard databases
 for i in zu5xai01 zu5xai03
 do
 echo ' '
 echo "Restoration status for $i@`hostname`"
 echo "-------------------------------------------"
 su - $i -c "db2 list utilities show detail"
 echo ' '
 done
-- For checking active status and the last logged message in .log
 for i in za3xat01 za3xat03 za3xat07
 do
 echo ''
 echo "Database $i@`hostname`"
 echo "----------------------------"
 su - $i -c "db2 list active databases;echo '';echo 'from diag.log -';echo '';cat sqllib/db2dump/db2diag.log|tail -15"
 echo ''
 done
-- For taking offline backup to local FS
 for i in zaexap40 zaexap41 zaexap42 zaexap43 zaexap44 zaexap45 zaexap46 zaexap47
 do
 echo "Database $i@`hostname`"
 echo "----------------------------"
 su - $i -c "db2 connect to $i;db2 'call get_dbsize_info(?,?,?,-1)';db2 terminate"
 echo ''
 done
 root@s96cd2d1:/db2_omnib/TT9928633 : for i in zaexap40 zaexap41 zaexap42 zaexap43 zaexap44 zaexap45 zaexap46 zaexap47
 do
 echo "Database $i@`hostname`"
 echo "----------------------------"
 su - $i -c "mkdir /db2_omnib/TT9928633/$i "
 echo ''
 root@s96cd2d1 > do> done

 for i in zaexap40 zaexap41 zaexap42 zaexap43 zaexap44 zaexap45 zaexap46 zaexap47
 do
 echo "Database $i@`hostname`"
 echo "----------------------------"
 su - $i -c "db2stop force;db2start;db2 backup db $i to /db2_omnib/TT9928633/$i/ "
 echo ''
 done
-- For checking locks in a server
 for i in zujxap01 zujxap02 zujxap03 zujxap04 zujxap05
 do
 echo ''
 echo "Database $i@`hostname`"
 echo "----------------------------"
 su - $i -c "db2 get snapshot for all applications|egrep -i 'held|handle'; db2 get snapshot for locks on $i|grep -i 'Table Name'|sort -u; db2 get snapshot for locks on $i|grep -i 'Tablespace Name'|sort -u; db2 get snapshot for locks on $i|grep -i 'Table Schema'|sort -u"
 echo ''
 done

how to interpret error in db2diag.log
=========================================

   Example:  2008-09-19-09.58.01.887762+120 I3253534C487       LEVEL: Error
  PID     : 13806                TID  : 1           PROC : db2agent () 0
  INSTANCE:              NODE : 000         DB   :
  APPHDL  : 0-48                 APPID: *LOCAL..080919075801
  FUNCTION: DB2 UDB, buffer pool services, sqlbinit, probe:540
  RETCODE : ZRC=0x850F0081=-2062614399=SQLO_SSEM_EXCEED_MAX
     "Requesting too many semaphores"
     DIA8336C Requested too many semaphores

   Action : db2diag -rc 0x850F0081
  Input ZRC string '0x850F0081' parsed as 0x850F0081 (-2062614399).
  ZRC value to map: 0x850F0081 (-2062614399)
   V7 Equivalent ZRC value: 0xFFFFD681 (-10623)
  ZRC class :
   Resource Capacity Error (Class Index: 5)
  Component:
   SQLO ; oper system services (Component Index: 15)
  Reason Code:
   129 (0x0081)
  Identifer:
   SQLO_SSEM_EXCEED_MAX
  Identifer (without component):
   SQLZ_RC_MAX_SEM
  Description:
   Requesting too many semaphores
  Associated information:
          Sqlcode -902
  SQL0902C  A system error (reason code = "") occurred.  Subsequent SQL
  statements cannot be processed.

          Number of sqlca tokens : 1
          Diaglog message number: 8336

 @s96dbt01:/home//sqllib/db2dump : db2 ? SQL0902C


  SQL0902C A system error (reason code = "")
            occurred.  Subsequent SQL statements cannot be
            processed.

  Explanation:

  A system error occurred.

  User Response:

  Record the message number (SQLCODE) and reason code in the
  message.

   If trace was active, invoke the Independent Trace Facility at
  the operating system command prompt.  Then contact your technical
  service representative with the following information:

  o   Problem description

  o   SQLCODE and embedded reason code

  o   SQLCA contents if possible

  o   Trace file if possible.



   Federated system users: isolate the problem to the data source
  failing the request (refer to the problem determination guide to
  determine which data source is failing to process the SQL
  statement) and take the necessary diagnostic steps for that data
  source.  The problem determination procedures for data sources
  vary, so refer to the applicable data source manuals.

   sqlcode :  -902

   sqlstate :  58005

  @s96dbt01:/home//sqllib/db2dump : db2 ? "SQL1040"


  SQL1040N The maximum number of applications is already connected
            to the database.

  Explanation:

  The number of applications connected to the database is equal to
  the maximum value defined in the configuration file for the
  database.

   The command cannot be processed.

  User Response:

  Wait for other applications to disconnect from the database.  If
  more applications are required to run concurrently, increase the
  value for maxappls .  After all applications disconnect from the
  database and the database is restarted, the new value takes
  effect.

   sqlcode :  -1040

   sqlstate :  57030



DB2 commands
============
For uploading the db2 instance details for PMR  - db2support . -d -cl 0
To find out who is the fenced user  - Check the owner of the file /sqllib/adm/.fenced
DB2 max connections exceeded   - db2 get dbm cfg |grep -i max
        ps -ef | grep |wc -l
        db2 get dbm cfg |grep -i agents
        db2pd -agents|head
       
Backup and restore parallelism
==============================

Go to the > db2_omnib > > > > usetsm > issue ls -ltr|tail > cd
   check file name like ora_adsm.result.0


root@s96gsuc1:/root : ora_omnib -l s96fbc1-200902081900
09.02.09 06:35:55 (s96gsuc1-l) Logfile '/log/ora_omnib/detail/s96fbc1.200902081900'
08.02.09 19:00:07 (s96fbc1-T) Begin s96fbc1-200902081900-TM
08.02.09 19:00:07 (s96fbc1-T) Perform total Backup of Oracle/DB2 and Unix
08.02.09 19:00:08 (s96fbc1-T) Override REDOXNODE=53.71.190.62
08.02.09 19:00:09 (s96fbc1-T) Found dsm.sys Address '172.17.126.21'
08.02.09 19:00:09 (s96fbc1-T) Set OMNIHOST to 's96tsm09'
08.02.09 19:00:10 (s96fbc1-T) Set ROBOT to '1'
08.02.09 19:00:13 (s96fbc1-T) Notice, create Flagfile '/sysadm/utils/ora_adsm.act.s96fbc1.O'
08.02.09 19:00:23 (s96fbc1-T) Access remote Oracle/DB2 Kontext, possibly DB2 Backup
08.02.09 19:00:24 (s96fbc1-T) Remote Call '/tmp/ora_adsm -GO s96fbc1.OM_omnib'
08.02.09 18:00:24*(s96fbc1-G) Invoked '/cluster/s96fbc1/glockware/sysadm/utils/ora_adsm -GO s96fbc1.OM_omnib'
08.02.09 18:00:24*(s96fbc1-G) Set OMNIHOST to '.'
08.02.09 18:00:24*(s96fbc1-G) Set ROBOT to '1'
08.02.09 18:00:24*(s96fbc1-G) Notice, Option 'G1' detected
08.02.09 18:03:27*(s96fbc1-G) Invoke DB2 Backup Pass
08.02.09 18:03:29*(s96fbc1-G) Node 's96fbc1' has 16 Filesystems
08.02.09 18:03:38*(s96fbc1-G) DB2 Database 'ZU5XAP01=0', Instance 'zu5xap01' found
08.02.09 18:03:38*(s96fbc1-G) Notice, check DB2 INCLUDE LOGS 'zu5xap01.ZU5XAP01=0'
08.02.09 18:04:09*(s96fbc1-G) Longest Dump has 239292416 Byte, Space for 3 more Dumps..
08.02.09 18:04:09*(s96fbc1-G) DB2 Dump to '/db2_omnib/s96fbc1/zu5xap01/ZU5XAP01=0/20090208180023'
08.02.09 18:04:09*(s96fbc1-G) Invoke 'backup db ZU5XAP01 online use tsm open 2 sessions with 8 buffers buffer 8000 paralle
lism 16 without prompting'
08.02.09 23:13:50*(s96fbc1-G) Warning, Error '2025' at DB2 online Backup 'ZU5XAP01=0'
08.02.09 23:13:51*(s96fbc1-G) DB2 Database 'ZU5XAP02=0', Instance 'zu5xap02' found
08.02.09 23:13:51*(s96fbc1-G) Notice, check DB2 INCLUDE LOGS 'zu5xap02.ZU5XAP02=0'
08.02.09 23:14:21*(s96fbc1-G) Longest Dump has 239292416 Byte, Space for 3 more Dumps..
08.02.09 23:14:21*(s96fbc1-G) DB2 Dump to '/db2_omnib/s96fbc1/zu5xap02/ZU5XAP02=0/20090208180023'
08.02.09 23:14:21*(s96fbc1-G) Invoke 'backup db ZU5XAP02 online use tsm open 1 sessions with 2 buffers buffer 2048 paralle
lism 1 without prompting'
08.02.09 23:19:40*(s96fbc1-G) Instance 'ZU5XAP02=0' backed up (C)
08.02.09 23:19:40*(s96fbc1-G) DB2 Database 'ZU5XAP04=0', Instance 'zu5xap04' found
08.02.09 23:19:40*(s96fbc1-G) Notice, check DB2 INCLUDE LOGS 'zu5xap04.ZU5XAP04=0'
08.02.09 23:20:15*(s96fbc1-G) Longest Dump has 239292416 Byte, Space for 3 more Dumps..
08.02.09 23:20:15*(s96fbc1-G) DB2 Dump to '/db2_omnib/s96fbc1/zu5xap04/ZU5XAP04=0/20090208180023'
08.02.09 23:20:15*(s96fbc1-G) Invoke 'backup db ZU5XAP04 online use tsm open 1 sessions with 2 buffers buffer 2048 paralle
lism 1 without prompting'
08.02.09 23:21:20*(s96fbc1-G) Instance 'ZU5XAP04=0' backed up (C)
08.02.09 23:21:21*(s96fbc1-G) Max.Redolength 1000000 Byte
09.02.09 00:21:55 (s96fbc1-T) Break, DB2 Backup failed
09.02.09 00:21:56 (s96fbc1-T) Error 2025 User 'zu5xap01', Instance 'ZU5XAP01=0' (An I/O error "-50" occurred on media "TSM
".)
09.02.09 00:21:58 (s96fbc1-T) End s96fbc1-200902081900-TM-2025-321-s96gsuc1-0-1659248
09.02.09 06:36:12 (s96gsuc1-l) Done
root@s96gsuc1:/root :       

RESTORE DATABASE ZU5XAP01
    USE TSM
    OPEN 2 SESSIONS
    TAKEN AT 20090206180425
    INTO ZU5XAI01
    -- NEWLOGPATH /onlineredo/ZU5XAI01/NODE0000
    WITH 8 BUFFERS BUFFER 8000
    REDIRECT
    PARALLELISM 8
;

DB2 SQLs
========
db2 "select substr(TABNAME,1,15) TABNAME , CASE TYPE WHEN 'A' THEN ' Alias' WHEN 'H' THEN 'Hierarchy table' WHEN 'N' THEN 'Nickname'  WHEN 'S' THEN 'Materialized query table'  WHEN 'T' THEN 'Table' WHEN 'U' THEN 'Typed table'  WHEN 'v' THEN 'View' WHEN 'W' THEN 'Typed vew' END  TYPE from syscat.tables where status='C' and TABSCHEMA='MIF_DEV'"

Create db with default tablespaces in desired location
======================================================

create database fk1xat03 using codeset UTF-8 territory DE catalog tablespace managed by database using ( file '/db2_data/FK1XAT03/system1/SYSCATSPACE_1.dat' 165320 ) extentsize 4 prefetchsize 16 temporary tablespace managed by system using ('/db2_data/FK1XAT03/temp1sms/TEMPSPACE1_1' ) extentsize 32 prefetchsize 32 user tablespace managed by database using ( file '/db2_data/FK1XAT03/data1/USERSPACE1_1.dat' 60000 ) extentsize 32 prefetchsize 32;

update parameter CATALOGCACHE_SZ
=================================
db2 update db cfg for fk1xat03 using CATALOGCACHE_SZ -1
$ cat db2look_mifdev.log | grep -i SQL | sort -u
$ cat db2look_mifdev.log | egrep "SQL0|DB20" | grep -v "DB20000I" | grep -v "ALTER"

   nohup db2 restore db vl6xap02 logs use TSM taken at 20110523030248  logtarget /onlineredo/VL6XAQ01/NODE0000/ &

Oracle WS

        ==================================
        WorkSheets - Oracle Database
        ==================================

 -------------------------
 Utilities and How to use:
 -------------------------
 orapwd file= password= entries=100
 ----------------------
 How to create logfile:
 ----------------------
 Run SQL file from OS - sqlplus "/ as sysdba" @test.sql > test.$(date +"%d%m%Y%H%M%S").log 2>&1

  Select database user process other than system processs - ps -ef|grep -i $ORACLE_SID|egrep -v "_$ORACLE_SID|arch"|grep -v grep

 ---------------------------------------------------------
 -- Shell script to execute script in multiple databases:
 ---------------------------------------------------------
cat > chkdb.sh

#!/usr/bin/ksh
for i in `ps -ef|grep pmon | grep ora | grep -v grep | awk '{print $NF}' | cut -c10-40`
do
        USER=`ps -ef|grep $i | grep pmon | awk '{print $1}'`
        DB=$i
        echo $DB   $USER
        su - $USER -c "export ORACLE_SID=$DB;sqlplus '/ as sysdba' @/root/test/chkdbversion.sql"  < /dev/null
done
--------------
-- Example 2:
--------------
#!/usr/bin/ksh
cat /sysadm/utils/ora_util.sid.. | awk '{print $2}' > /tmp/dblist
for i in `cat /tmp/dblist`
do
        USER=`ps -ef|grep $i | grep pmon | awk '{print $1}'`
        DB=$i
        echo $DB   $USER
        su - $USER -c "export ORACLE_SID=$DB;sqlplus '/ as sysdba' @/oracle/product/tbsspace.sql"  < /dev/null
done

-------------------
-- Create SQL file:
-------------------
cat > .sql
spool .sql
set heading off feedback off echo off verify off
;
spool off

@.sql
@;

=========================
1) Checking oracle error:
=========================
-----------------------------------
1.1) Check oracle error definition:
-----------------------------------
Issue - oerr ora - as oracle user
 Example:
  ora_WE@s96md0d1:/oracle/log/MDPWE/bdump : oerr ora 02068
  02068, 00000, "following severe error from %s%s"
  // *Cause: A severe error (disconnect, fatal Oracle error) received from
  //         the indicated database link.  See following error text.
  // *Action: Contact the remote system administrator.
  ora_WE@s96md0d1:/oracle/log/MDPWE/bdump :
  ora_WE@s96md0d1:/oracle/log/MDPWE/bdump :
-------------------------------
1.2) Find trace file in Oracle:
-------------------------------
 The following script returns the path to the trace file that the current session writes.
 It returns the path whether or not tracing is enabled.
select u_dump.value
  ||  '/'
  ||  db_name.value
  ||  '_ora_'
  ||  v$process.spid
  ||  nvl2(v$process.traceid,'_'
  ||  v$process.traceid,null)
  ||  '.trc' trcfile
from v$parameter u_dump
cross join v$parameter db_name
cross join v$process
join v$session
on v$process.addr    = v$session.paddr
where u_dump.name    = 'user_dump_dest'
and db_name.name     = 'db_name'
and v$session.audsid = sys_context('userenv','sessionid')
and v$session.sid    =
  (select distinct sid from v$mystat)
and v$session.serial# =
  (select serial# from v$session where sid =
    (select distinct sid from v$mystat))
/
In order to generate a more informative trace file name, the following command can be used:
alter session set tracefile_identifier = here_is_my_session;
 A trace file will then have this identifier (here: here_is_my_session) in it's filename.
 The trace file's name can also be found with oradebug:
SQL> oradebug setmypid
SQL> oradebug tracefile_name
*/
--------------
-- Last alert:
--------------
set linesize 145 pagesize 1000  trimout on trimspool on feedback off timing off verify off
column ct                          format a18              heading  "Creation Time"
column instance_name               format a8               heading  "Instance|Name"
column object_type                 format a14              heading  "Object|Type"
column message_type                format a9               heading  "Message|Type"
column message_level               format 9999             heading  "Mess.|Lev."
column reason                      format a30              heading  "Reason"
column suggested_action            format a75              heading  "Suggested|Action"
Select 
       To_Char(Creation_Time, 'DD-MM-YYYY HH24:MI') ct
     , instance_name         
     , object_type           
     , message_type        
     , message_level      
     , reason            
     , suggested_action 
  From
       dba_outstanding_alerts
 Order
     By Creation_Time
;
====================
3) Initial Queries:
====================
------------------------
-- Identify own session:
------------------------
select s.username,
  p.spid,
  s.sid,
  s.serial#
from v$session s,
  v$process p
where s.paddr = p.addr
and s.type    = 'USER'
and s.sid     = sys_context('USERENV', 'SID')
and s.sid     =
  (select distinct sid from v$mystat)
and s.serial# =
  (select serial#
  from v$session
  where sid=
    (select distinct sid from v$mystat))
/
-------------------------------
-- Identify the number of CPUs:
-------------------------------
select value
from   v$osstat
where  stat_name='NUM_CPUS'
/
-----------------------------------------------
-- Instance details (startup time, status etc:)
-----------------------------------------------
col HOST_NAME for a12
col STARTUP_TIME for a20
col INSTANCE_NAME for a12
SELECT SUBSTR(host_name,0,15) host_name, instance_name, status,TO_CHAR(startup_time,'dd-mm-yy hh24:mi:ss') startup_time
FROM   v$instance
/
------------------------------------------------------
-- Instance details ( startup time using pmon process)
------------------------------------------------------
SELECT to_char(logon_time,'Dy dd Mon HH24:MI:SS') "DB Startup Time"
FROM   sys.v_$session
WHERE  sid=1   /* this is pmon */
/
----------------------------------------------------------------------------------
-- Database details (Open mode, log mode (archive/no archive), force logging etc:)
----------------------------------------------------------------------------------
SELECT name, dbid, open_mode, log_mode, force_logging
FROM   v$database
/
--------------------------
-- Database Charactre set:
--------------------------
-- The (ordinary) character set for a database
select value from nls_database_parameters where parameter = 'NLS_CHARACTERSET';
--The national character set for a database
select value from nls_database_parameters where parameter = 'NLS_NCHAR_CHARACTERSET';
-- Current database character set from system view
select value$ from sys.props$ where name='NLS_CHARACTERSET';
------------------
-- Database size :
------------------
-- Database size (except control files):
col database format a20
col host format a20
select trim(ora_database_name) database,
       e.host_name host,
       round((a.data_size+b.temp_size+c.redo_size),2) total_gb ,
       round((a.data_size+b.temp_size+c.redo_size) - d.free_size,2) used_gb,
       round(d.free_size,2) free_gb
from ( select sum(bytes)/1024/1024/1024 data_size from dba_data_files ) a,
     ( select nvl(sum(bytes)/1024/1024/1024,0) temp_size from dba_temp_files ) b,
     ( select sum(bytes)/1024/1024/1024 redo_size from sys.v_$log ) c ,
     ( select sum(bytes)/1024/1024/1024 FREE_SIZE from dba_free_space ) d ,
     ( select trim(host_name) host_name from v$instance ) e
/
-- Database size (except control files, on max size):
set linesize 100
col database format a20
col host format a20
select trim(ora_database_name) database,
       e.host_name host,
       round((a.data_size+b.temp_size+c.redo_size),2) total_gb ,
       round((a.data_size+b.temp_size+c.redo_size) - d.free_size,2) used_gb,
       round(d.free_size,2) free_gb,
       round((a.data_size_max+b.temp_size_max+c.redo_size),2) max_gb
from ( select nvl(sum(bytes)/1024/1024/1024,0) data_size, nvl(sum(maxbytes)/1024/1024/1024,0) data_size_max from dba_data_files ) a,
     ( select nvl(sum(bytes)/1024/1024/1024,0) temp_size, nvl(sum(maxbytes)/1024/1024/1024,0) temp_size_max  from dba_temp_files ) b,
     ( select nvl(sum(bytes)/1024/1024/1024,0) redo_size from sys.v_$log ) c ,
     ( select nvl(sum(bytes)/1024/1024/1024,0) free_size from dba_free_space ) d ,
     ( select trim(host_name) host_name from v$instance ) e
/

--------------------
-- Controlfile size:
--------------------
set termout off
column value new_value BlkSz
select value
from sys.v_$parameter
where name = 'db_block_size'
/

set termout on
set verify off
select &BlkSz * (1 + 2 * sum(ceil(record_size * records_total / (&BlkSz - 24)))) bytes
from sys.v_$controlfile_record_section
/
--> Testing
select (f.value * g.bytes) * (select count(*) from v$controlfile) ctrl_size
from
(select value from sys.v_$parameter where name = 'db_block_size') f,
(select (1 + 2 * sum(ceil(record_size * records_total / ((select value from sys.v_$parameter where name = 'db_block_size') - 24)))) bytes from sys.v_$controlfile_record_section)g
/
--< Testing
-------------------------------
-- Background Process details :
-------------------------------
set pagesize 60 lines 1000
col program format a30
col osuser format a30
select p.spid   osprocess,
       s.osuser osuser   ,
       s.program         ,
       s.status          ,
       to_char(logon_time,'dd-mm-yy hh24:mi:ss') logon_time
from   v$process p,
       v$session s
where  p.addr       = s.paddr
and    s.type       = 'BACKGROUND'
and    p.background =1
/
----------------------------------
-- File structure,status and size:
----------------------------------
------------------------------------------------
-- 1.)File count for Control/Data/Redolog files:
------------------------------------------------
SELECT (SELECT COUNT(NAME)
        FROM   v$controlfile) control_files,
       (SELECT COUNT(NAME)
        FROM   v$datafile) data_files,
       (SELECT COUNT(MEMBER)
        FROM   v$logfile) redolog_fiels,
       (SELECT COUNT(NAME)
        FROM   v$tempfile) temp_files
FROM   dual
/
------------------------------------------------
-- 2.)File count for Control/Data/Redolog files:
------------------------------------------------
col file_name for a40
SELECT SUBSTR(NAME,0,55) file_name,status FROM   v$controlfile
UNION ALL
SELECT SUBSTR(NAME,0,55) file_name,status FROM   v$datafile
UNION ALL
SELECT SUBSTR(MEMBER,0,55) file_name,status FROM   v$logfile
UNION ALL
SELECT SUBSTR(file_name,0,55) file_name,status FROM   dba_data_files
/
--------------------------------------------------
-- 3.) File status for Control/Data/Redolog files:
--------------------------------------------------
SELECT DISTINCT status FROM   v$controlfile
UNION ALL
SELECT DISTINCT status FROM   v$datafile
UNION ALL
SELECT DISTINCT status FROM   v$tempfile
UNION ALL
SELECT DISTINCT status FROM   v$logfile
UNION ALL
SELECT DISTINCT status FROM   dba_data_files
/
------------------------------------------------------------------------------
-- 4.) Structure - (File count for Control/Data/Redolog files Including size):
------------------------------------------------------------------------------
SELECT (SELECT COUNT(NAME)
        FROM   v$controlfile) control_files,
       (SELECT COUNT(NAME)||' (Size(GB): '||ROUND(SUM(bytes)/1024/1024/1024,2)||')'
        FROM   v$datafile) data_files,
       (SELECT COUNT(MEMBER)
        FROM   v$logfile) redolog_files,
       (SELECT COUNT(NAME)||' (Size(GB): '||ROUNd(SUM(bytes)/1024/1024/1024,2)||')'
        FROM   v$tempfile) temp_files
FROM   dual
/
------------------------------------------------
-- 5.) Structure - (File location for database):
------------------------------------------------
select distinct substr(name,0,instr(name,'/',-1,1)) file_path from  v$datafile;
select distinct substr(name,0,instr(name,'/',-1,1)) file_path from  v$controlfile;
select distinct substr(member,0,instr(member,'/',-1,1)) file_path from  v$logfile;
select distinct substr(name,0,instr(name,'/',-1,1)) file_path from  v$tempfile;
select decode(value,null,(select substr(file_spec,0,instr(file_spec,'/lib/libqsmashr.so' ))||'dbs/'
        from dba_libraries
        where library_name = 'DBMS_SUMADV_LIB'
      ),substr(value,0,instr(value,'/',-1,1))) file_path
from sys.v_$parameter
where name = 'spfile';

select distinct file_path
from
(select distinct substr(name,0,instr(name,'/',-1,1)) file_path from  v$datafile
 union all
 select distinct substr(name,0,instr(name,'/',-1,1)) file_path from  v$controlfile
 union all
 select distinct substr(member,0,instr(member,'/',-1,1)) file_path from  v$logfile
 union all
 select distinct substr(name,0,instr(name,'/',-1,1)) file_path from  v$tempfile
 union all
 select destination from v$archive_dest where destination is not null
 union all
 select decode(value,null,(select substr(file_spec,0,instr(file_spec,'/lib/libqsmashr.so' ))||'dbs/'
         from dba_libraries
         where library_name = 'DBMS_SUMADV_LIB'
       ),substr(value,0,instr(value,'/',-1,1))) file_path
 from sys.v_$parameter
 where name = 'spfile')
/
---------------------------------------------------------------
-- 6.) Structure - (Parameter file using for instance startup):
---------------------------------------------------------------
SELECT NVL(value,
       (SELECT SUBSTR(file_spec,0,instr(file_spec,'/lib/libqsmashr.so' ))
       FROM    DBA_LIBRARIES
       WHERE   library_name = 'DBMS_SUMADV_LIB')
              ||'dbs/init'
              ||lower(trim(ora_database_name))||'.ora') parfile
FROM   v$parameter
WHERE  name='spfile'
/
-----------------------------------------------------------------------------------
-- Database details (Database open mode, archive log mode etc:)- depends on version
-- ** Wrong query**
-----------------------------------------------------------------------------------
select substr(trim(substr(banner,(select instr(banner,'Release') from v$version where rownum=1),(select instr(banner,'-') from v$version where rownum=1)-(select instr(banner,'Release') from v$version where rownum=1))),0,25) version from v$version where rownum=1;
SELECT NAME,
       open_mode,
       log_mode,
       DECODE((SELECT SUBSTR(banner,(SELECT INSTR(LOWER(banner),'release',1,1)
                                     FROM   v$version
                                     WHERE  ROWNUM = 1) + LENGTH('release') + 1,
                             ((SELECT INSTR(LOWER(banner),'.',1,1)
                               FROM   v$version
                               WHERE  ROWNUM = 1) - ((SELECT INSTR(LOWER(banner),'release',1,1)
                                                      FROM   v$version
                                                      WHERE  ROWNUM = 1) + LENGTH('release') + 1)))
               FROM   v$version
               WHERE  ROWNUM = 1),'8','Not applicable','9',force_logging,'10',force_logging) force_logging
FROM   v$database
/
--------------------------------------------------
-- Database details(After database copy/recreation)
---------------------------------------------------
SELECT NAME, TO_CHAR(created,'dd-mm-yy hh24:mi:ss') created ,open_mode, log_mode, force_logging
FROM   v$database
/
------------------------------------------
-- Before/After a successful upgradation:
------------------------------------------
select * from v$version;
SELECT comp_id, version, status FROM dba_registry;
Identify successful upgradation from alert.log
cat | grep  "SERVER COMPONENT" -->  Its status should be VALID
-----------------------------------------------------------------------------------------
-- Database backup information (Database name,backup level,start time,elapsed time etc: )
-----------------------------------------------------------------------------------------
select count(*) from v$backup where status <> 'NOT ACTIVE';

SELECT DECODE(DECODE ((SELECT COUNT (file#)
                           FROM v$backup
                          WHERE status = 'ACTIVE'),(SELECT COUNT (file#)
            FROM v$datafile)
                        , 'D', 0, 'N', 'T')
         ,'D',
         (SELECT CHR (9)
              || CHR (10)
              || CHR (10)
              || 'Database '
              || UPPER(TRIM(ora_database_name))
              || ' in full backup mode..'
              || CHR (10)
              || RPAD('~',LENGTH('Database '||upper(trim(ora_database_name))||' in full backup mode..'),'~')
              || CHR (10)
              || 'Start time         : '
              || TO_CHAR (MIN (TIME), 'dd-mm-yyyy hh24:mi:ss')
              || CHR (10)
              || 'Current time       : '
              || TO_CHAR (SYSDATE, 'dd-mm-yyyy hh24:mi:ss')
              || CHR (10)
              || 'Elapsed time(mins) : '
              || ROUND (TO_NUMBER (SYSDATE - MIN (TIME)) * 1440)
              || CHR (10)
              || 'Elapsed time(Hrs)  : '
              || ROUND ((TO_NUMBER (SYSDATE - MIN (TIME)) * 1440) / 60, 2)
              || CHR (10)
            FROM v$backup)
         ,'T',
         (SELECT COUNT(DISTINCT ts#)
       ||' Tablespace(S) in backup mode'
            FROM v$datafile
           WHERE file# IN
                 (SELECT file#
                    FROM    v$backup
                   WHERE   STATUS ='ACTIVE'))
         ,'N','Database/Tablespace not in backup mode') AS bkp_info
FROM   DUAL
/
----------------
-- Transaction :
----------------
-- List long running transaction (Here for a RMAN session)
--
SET linesize 1000 pagesize 60 lines 1000
SELECT sid, serial#, context, sofar, totalwork,
       round(sofar/totalwork*100,2) "%_COMPLETE",
       time_remaining, elapsed_seconds
FROM v$session_longops
WHERE opname LIKE 'RMAN%'
  AND opname NOT LIKE '%aggregate%'
  AND totalwork != 0
  AND sofar <> TOTALWORK
/
SET linesize 1000 pagesize 60 lines 1000
SELECT sid, serial#, context, sofar, totalwork,
       round(sofar/totalwork*100,2) "%_COMPLETE",
       time_remaining, elapsed_seconds
FROM v$session_longops
WHERE sid =
  AND totalwork != 0
/

-----------------
-- RMAN Progress:
-----------------
BGRED=`echo "\033[41m"`
NORMAL=`echo "\033[m"`
echo "----------------------------------------------------"
echo "${BGRED} `ps -ef| grep rman|grep -iv grep` ${NORMAL}"
echo "----------------------------------------------------"
tail -4 restore_HREPPRD9.log
sqlplus "/as sysdba" << EOF
@RMAN_prog_monitor.sql
exit
EOF

-----------------------
-- Start RMAN in nohup:
-----------------------
nohup rman cmdfile=hrepprd9_duplicate_rman.rcv log=hrepprd9_duplicate_rman.log &
------------------------
-- Monitor RMAN session:
------------------------
--------------------------------------------------------------
-- Lists ongoing RMAN session
-- Note: Informations like time remaining, session information
--   has been added
--------------------------------------------------------------
set linesize 100 pagesize 60 lines 1000
--
column client_info format a30
column sid format 999999
column spid format 999999
--
prompt
prompt INFO: RMAN session information:
prompt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
prompt
--
select s.sid ,
       p.spid,
       s.client_info
from   v$process p,
       v$session s
where  p.addr         = s.paddr
and    client_info like 'rman%'
/
prompt
prompt INFO: RMAN Progress:
prompt ~~~~~~~~~~~~~~~~~~~~
prompt
--
select sid                                      ,
       serial#                                  ,
       context                                  ,
       sofar                                    ,
       totalwork                                ,
       round(sofar/totalwork*100,2) "% Complete",
       time_remaining "Time remaining(secs)"    ,
       elapsed_seconds "Elapsed time(secs)"     ,
from   v$session_longops
where  opname     like 'RMAN%'
and    opname not like '%aggregate%'
and    totalwork    != 0
and    sofar        <> totalwork
/
prompt


--------------------------------------------------------------
-- Datafile backup mode ( details like file id,file name etc:)
--------------------------------------------------------------
SELECT SUBSTR(TO_CHAR(a.file#),0,4) "File ID",
       SUBSTR(b.NAME,0,60)          "File name",
       SUBSTR(a.status,0,10)        "Status"
FROM   v$backup a,
       v$datafile b
WHERE  a.file# = b.file#
/
-----------------------
-- Checking parameters
-----------------------
show parameter background_dump_dest;
archive log list;

 ================
3) Space management
 ================

1) Database level:
----------------------------
-- To find the database size
----------------------------
clear columns
clear breaks
set linesize 1000
set termout on
set feedback off
set verify off
set pagesize 0
set echo off
set recsep off
set time off
set timing off
set pagesize 60
set verify off
set lines 1000
set numwidth 11
set heading on
set wrap off
set trimspool on
column name format a9 heading "Database"
column host_name format a12 heading "Host"
column space_granted_gb format a17 heading "Space Granted(GB)"
column max_space_avilable_gb format a22 heading "Max Space Avilable(GB)"
column used_space_gb format a14 heading "Used Space(GB)"
column free_space_gb format a14 heading "Free Space(GB)"
column used_on_granted format a22 heading "%Used on Space Granted"
column used_on_avilable format a27 heading "%Used on Max Space Avilable"
--
--
SELECT SUBSTR(SUBSTR (ora_database_name, 1, LENGTH (ora_database_name)),0,8) name,
       SUBSTR(e.host_name,0,15) host_name,
       TO_CHAR(SUBSTR(ROUND ((a.data_size + b.temp_size + c.redo_size), 2 ),0,17)) space_granted_gb,
       TO_CHAR(SUBSTR(ROUND ((a.data_size_max + b.temp_size + c.redo_size), 2 ),0,22)) max_space_avilable_gb,
       TO_CHAR(SUBSTR(ROUND ((a.data_size + b.temp_size + c.redo_size) - d.free_size, 2 ),0,14)) used_space_gb,
       TO_CHAR(SUBSTR(ROUND (d.free_size, 2),0,14)) free_space_gb,
       TO_CHAR(SUBSTR(ROUND (  (  ((a.data_size + b.temp_size + c.redo_size) - d.free_size)
                 / (a.data_size + b.temp_size + c.redo_size) ) * 100, 2 ),0,22)) used_on_granted,
       TO_CHAR(SUBSTR(ROUND (  (  ((a.data_size + b.temp_size + c.redo_size) - d.free_size)
                 / (a.data_size_max + b.temp_size + c.redo_size) ) * 100, 2 ),0,27)) used_on_avilable
  FROM (SELECT SUM (BYTES) / 1024 / 1024 / 1024 data_size,  SUM (DECODE (maxbytes, 0, BYTES, maxbytes)) / 1024 / 1024 / 1024 data_size_max
          FROM dba_data_files) a,
       (SELECT NVL (SUM (BYTES) / 1024 / 1024 / 1024, 0) temp_size
          FROM dba_temp_files) b,
       (SELECT SUM (BYTES) / 1024 / 1024 / 1024 redo_size
          FROM SYS.v_$log) c,
       (SELECT SUM (BYTES) / 1024 / 1024 / 1024 free_size
          FROM dba_free_space) d,
       (SELECT host_name
          FROM v$instance) e
/

2) Tablespace level:(Normal tablesapce)
------------------------------------------------
-- To find the max size possible for a datafile:
------------------------------------------------
SELECT TO_CHAR(4194303 * VALUE,'999,999,999,999') max_bytes,
       TO_CHAR(TRUNC(4194303 * VALUE / 1024),'999,999,999')||' Kb' max_kb,
       TO_CHAR(TRUNC(4194303 * VALUE / 1024 / 1024),'999,999')||' Mb' max_mb
FROM   v$parameter
WHERE  NAME = 'db_block_size'
/
----------------------------------------------------
-- To find the tablespace usage metrics (In blocks):
----------------------------------------------------
SELECT * FROM   dba_tablespace_usage_metrics;
---------------------------------------------------
-- To find the tablespace usage metrics (In bytes):
---------------------------------------------------
-- Applicabale only 10g.x and above
-- With TEMP_TABLESPACE
SELECT   b.tablespace_name                                                                                     ,
         NVL(ROUND(SUM(DECODE(b.tablespace_name,c.tablespace_name,c.bytes,a.bytes))      /1024/1024,2),0) mb   ,
         NVL(ROUND(SUM(DECODE(b.tablespace_name,c.tablespace_name,c.maxbytes,a.maxbytes))/1024/1024,2),0) maxmb,
         NVL(ROUND(b.used_percent,2),0)                                                                   used_percent
FROM     dba_data_files a              ,
         dba_tablespace_usage_metrics b,
         dba_temp_files c
WHERE    a.tablespace_name(+)=b.tablespace_name
AND      c.tablespace_name(+)=b.tablespace_name
AND  b.tablespace_name=NVL(UPPER(TRIM('&tablespace_name')),a.tablespace_name)
GROUP BY b.tablespace_name,
         b.used_percent
ORDER BY used_percent DESC
/
-- Without TEMP_TABLESPACE
SELECT   b.tablespace_name                              ,
         NVL(ROUND(SUM(a.bytes)   /1024/1024,2),0) mb   ,
         NVL(ROUND(SUM(a.maxbytes)/1024/1024,2),0) maxmb,
         NVL(ROUND(b.used_percent,2),0)            used_percent
FROM     dba_data_files a,
         dba_tablespace_usage_metrics b
WHERE    a.tablespace_name=b.tablespace_name
AND  b.tablespace_name=NVL(UPPER(TRIM('&tablespace_name')),a.tablespace_name)
GROUP BY b.tablespace_name,
         b.used_percent
ORDER BY used_percent DESC
/
* tablespace usage metrics included temporary tablesapce usage
--------------------------------
-- To find the tablesapce quotas
--------------------------------
set linesize 120
col username format a30
col tbs format a30
set linesize 1000 pagesize 60 lines 1000
select   username                          username,
         tablespace_name                   tbs,
         round(sum(bytes)/1024/1024,2)     usedmb,
         decode(max_bytes,-1,'UNLIMITED',round(sum(max_bytes)/1024/1024),2) maxmb
from     dba_ts_quotas
where    username = NVL(UPPER(TRIM('&username')),username)
group by username, tablespace_name, max_bytes
/
-------------------------------------------------------
-- To find the tablesapce details in a formatted output
-------------------------------------------------------
set linesize 1000;
set termout on;
set feedback off;
set verify off;
set echo off;
set pagesize 60;
set lines 1000;
column tablespace_name format a15 heading "Tablespace";
column "avail MB" format 99999999;
column "free MB" format 99999999;
column "Used %" format 99999999;
--
--
SELECT   a.tablespace_name TABLESPACE,
         ROUND(a.bytes / 1024 / 1024,0) "avail MB",
         ROUND(f.bytes / 1024 / 1024,0) "free MB",
         ROUND((a.bytes - f.bytes) / a.bytes * 100,0) "Used %"
FROM     sm$ts_avail a,
         sm$ts_free f
WHERE    a.tablespace_name = f.tablespace_name
         AND a.tablespace_name = NVL(UPPER(TRIM('&tablespace_name')),a.tablespace_name)
ORDER BY 4 DESC
/
--------------------------------------------------------------------------------------------
-- To find the tablesapce details (file name,autoextensible,allocated space, max space etc:)
--------------------------------------------------------------------------------------------
SELECT   SUBSTR(file_name,0,80) file_name,
         autoextensible,
         SUM(bytes) / 1024 / 1024 mb,
         SUM(maxbytes) / 1024 / 1024 maxmb
FROM     dba_data_files
WHERE    tablespace_name = NVL(UPPER(TRIM('&tablespace_name')),tablespace_name)
GROUP BY file_name,
         autoextensible
ORDER BY file_name
/
---------------------------------------------------
-- To find the tablesapce details (name, contents):
---------------------------------------------------
SELECT tablespace_name,
       contents
FROM   dba_tablespaces
WHERE  tablespace_name IN (SELECT tablespace_name
                           FROM   dba_data_files
                           WHERE  file_name IN ( '&file_name' ))
/
--------------------------------------------------------------------------------------------
-- To find the tablesapce details (file_name,autoextensible,allocated space, max space etc:)
-- % used Calculated on max space)
--------------------------------------------------------------------------------------------
SET linesize 1000 pagesize 60 lines 1000 termout on feedback off verify off echo off;
COL tbs format a30
SELECT a.tbs,
       ROUND(a.mb,2)                                             alloc_mb,
       ROUND(a.mb - b.mb,2)                                      used_mb,
       ROUND(a.maxmb,2)                                          max_mb,
       ROUND(a.maxmb - (a.mb - b.mb),2)                                 free_mb,
       DECODE(a.mb,0,0,ROUND(((a.mb - b.mb) / a.mb) * 100,2))       pct_on_alloc,
       DECODE(a.maxmb,0,0,ROUND(((a.mb - b.mb) / a.maxmb) * 100,2))  pct_on_max,
       ROUND((((a.mb - b.mb)*100)/80),0)     target_size
       -- ROUND((((GREATEST(a.mb,a.maxmb) - b.mb)*100)/85),0)   target_size_test
FROM   (SELECT   tablespace_name                                       tbs,
                 NVL(SUM(bytes),0) / (1024 * 1024)                     mb,
                 NVL(SUM(GREATEST(bytes,maxbytes)),0) / (1024 * 1024)  maxmb
        FROM     dba_data_files
        GROUP BY tablespace_name) a,
       (SELECT   tablespace_name                   tbs,
                 NVL(SUM(bytes),0) / (1024 * 1024) mb
        FROM     dba_free_space
        GROUP BY tablespace_name) b
WHERE  a.tbs = b.tbs (+)
       AND a.tbs = NVL(UPPER(TRIM('&tbs')),a.tbs)
/

  SELECT SUBSTR (a.tbs, 0, 20) tbs,
         ROUND (NVL (a.bytes, 0) / 1024 / 1024, 2) alloc_mb,
         ROUND ((NVL (a.bytes, 0) - NVL (b.bytes, 0)) / 1024 / 1024, 2) used_mb,
         ROUND (NVL (a.maxbytes, 0) / 1024 / 1024, 2) max_mb,
         ROUND (NVL (a.maxbytes - (NVL (a.bytes, 0) - NVL (b.bytes, 0)), 0) / 1024 / 1024, 2) free_mb,
  DECODE (NVL (a.bytes, 0),0,0,ROUND (((NVL (a.bytes, 0) - NVL (b.bytes, 0)) / NVL (a.bytes, 0)) * 100, 2)) pct_on_alloc,
         DECODE (NVL (a.maxbytes, 0),0,0,ROUND (((NVL (a.bytes, 0) - NVL (b.bytes, 0)) / NVL (a.maxbytes, 0)) * 100, 2)) pct_on_max
    FROM (SELECT   tablespace_name tbs, NVL(SUM (bytes),0) bytes,
                   NVL(SUM
                          (CASE
                              WHEN (DECODE (maxbytes, 0, bytes, maxbytes) >= bytes)
                                 THEN DECODE (maxbytes, 0, bytes, maxbytes)
                              ELSE bytes
                           END
                      ),0) maxbytes
              FROM dba_data_files
          GROUP BY tablespace_name) a,
         (SELECT   tablespace_name tbs,
                   NVL (SUM (bytes), 0) bytes
              FROM dba_free_space
          GROUP BY tablespace_name) b
   WHERE a.tbs = b.tbs(+)
     AND a.tbs = NVL(UPPER(TRIM('&tablespace_name')),a.tbs)
ORDER BY DECODE (NVL (a.maxbytes, 0),0,0,ROUND (((NVL (a.bytes, 0) - NVL (b.bytes, 0)) / NVL (a.maxbytes, 0)) * 100, 2)) DESC
/

2) Tablespace level:(Temporary tablesapce)

--------------------------------
-- For ORA-1652 specific errors:
--------------------------------
SELECT property_value
FROM   database_properties
WHERE  property_name = 'DEFAULT_TEMP_TABLESPACE'
/

SELECT used_percent
FROM   dba_tablespace_usage_metrics
WHERE  tablespace_name=
       (SELECT property_value
       FROM    database_properties
       WHERE   property_name = 'DEFAULT_TEMP_TABLESPACE')
/

SELECT TABLESPACE_NAME,
       USED_PERCENT
FROM   dba_tablespace_usage_metrics
WHERE  TABLESPACE_NAME IN
       (SELECT tablespace_name
        FROM    dba_tablespaces
        WHERE   contents='TEMPORARY')
/

select name,sum(bytes)/1024/1024 mb from v$tempfile group by name;
-------------------------------------------------------
-- To calculate the free space in temporary tablespace:
-------------------------------------------------------
SELECT tablespace_name, bytes_used/1024/1024 used_mb, bytes_free/1024/1024 free_mb FROM v$temp_space_header;
select TABLESPACE_NAME,TOTAL_BLOCKS,USED_BLOCKS,FREE_BLOCKS,MAX_BLOCKS from v$sort_segment;
select sum(BLOCKS) from v$sort_usage where username='SYS';

/* DBA_FREE_SPACE does not record free space for temporary tablespaces.Use V$TEMP_SPACE_HEADER instead.*/
SELECT   SUM( u.blocks * blk.block_size)/1024/1024 "Mb. in sort segments",
         (hwm.max      * blk.block_size)/1024/1024 "Mb. High Water Mark"
FROM     v$sort_usage u,
         (SELECT block_size
         FROM    dba_tablespaces
         WHERE   contents = 'TEMPORARY') blk ,
         (SELECT segblk#+blocks MAX
         FROM    v$sort_usage
         WHERE   segblk# =
                 (SELECT MAX(segblk#)
                 FROM    v$sort_usage)) hwm
GROUP BY hwm.max * blk.block_size/1024/1024
/

SELECT tablespace_name,
       extent_size    ,
       total_extents  ,
       used_extents   ,
       free_extents   ,
       max_used_size
FROM   v$sort_segment
/

SELECT   a.tablespace,
         b.sid       ,
         b.serial#   ,
         a.blocks    ,
         c.sql_text
FROM     v$tempseg_usage a,
         v$session b      ,
         v$sqltext c
WHERE    a.session_addr = b.saddr
AND      b.sql_address  = c.address
AND      a.tablespace   = NVL(UPPER(TRIM('&tablespace_name')),
         (SELECT property_value
         FROM    database_properties
         WHERE   property_name = 'DEFAULT_TEMP_TABLESPACE'))
ORDER BY a.tablespace,
         b.sid       ,
         b.serial#   ,
         c.address   ,
         c.piece
/

-- Monitoring the temporary tablespace:
SELECT segtype,
       extents,
       blocks
FROM   v$tempseg_usage
WHERE  TABLESPACE = NVL(UPPER(TRIM('&tablespace_name')),
       (SELECT property_value
       FROM    database_properties
       WHERE   property_name = 'DEFAULT_TEMP_TABLESPACE'))
/
------------------------------------------------------------------------------------------------------
-- To find the temporary tablesapce details (file name,autoextensible,allocated space, max space etc:)
------------------------------------------------------------------------------------------------------
set linesize 1000;
set termout on;
set feedback off;
set verify off;
set echo off;
set pagesize 60;
set lines 1000;
column tablespace_name format a30;
column mb format 999999;
column increment_by format 999999;
column maxmb format 999999;
column autoextensible format a15;
--
--
SELECT   tablespace_name,
         SUM(bytes) / 1024 / 1024 mb,
         autoextensible,
         SUM(increment_by) / 1024 / 1024 increment_by,
         SUM(maxbytes) / 1024 / 1024 maxmb
FROM     dba_temp_files
WHERE    tablespace_name = NVL(UPPER(TRIM('&tablespace_name')),(SELECT property_value
                                                                FROM   database_properties
                                                                WHERE  property_name = 'DEFAULT_TEMP_TABLESPACE'))
GROUP BY tablespace_name,
         autoextensible
/
------------------------------------------------------------------------------------------------------------
-- To find the temporary tablesapce details (file name,autoextensible,allocated space, max space, file etc:)
------------------------------------------------------------------------------------------------------------
SELECT   SUBSTR(tablespace_name,0,20) TABLESPACE,
         SUBSTR(file_name,0,55) file_name,
         SUM(bytes) / 1024 / 1024 mb,
         SUBSTR(autoextensible,0,4) autoextensible,
         SUM(increment_by) / 1024 / 1024 increment_by,
         SUM(maxbytes) / 1024 / 1024 maxmb
FROM     dba_temp_files
WHERE    tablespace_name = (SELECT property_value
                            FROM   database_properties
                            WHERE  property_name = 'DEFAULT_TEMP_TABLESPACE')
GROUP BY tablespace_name,
         file_name,
         autoextensible
/
---------------------------------------------------------------------
-- To report true free space within the used portion of the TEMPFILE:
---------------------------------------------------------------------
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
/
----------------------------
-- To find HWM in datafiles:
----------------------------
/*
Note:
-----
The following script to generate alter database datafile '......' resize
commands to shrink files down to their smallest possible size.  Just bear in mind that
unless you have autoextend on -- if you shrink the file you just gave up all of that free
space.  You might not be able to extend your tables into new extents!
*/
--
set verify off
column file_name format a50 word_wrapped
column smallest format 999,990 heading "Smallest|Size|Poss."
column currsize format 999,990 heading "Current|Size"
column savings  format 999,990 heading "Poss.|Savings"
break on report
compute sum of savings on report
--
column value new_val blksize
select value from v$parameter where name = 'db_block_size'
/
--
select file_name,
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,
       ceil( blocks*&&blksize/1024/1024) currsize,
       ceil( blocks*&&blksize/1024/1024) -
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings
from dba_data_files a,
     ( select file_id, max(block_id+blocks-1) hwm
         from dba_extents
        group by file_id ) b
where a.file_id = b.file_id(+)
/
--
column cmd format a75 word_wrapped
--
select 'alter database datafile ''' || file_name || ''' resize ' ||
       ceil( (nvl(hwm,1)*&&blksize)/1024/1024 )  || 'm;' cmd
from dba_data_files a,
     ( select file_id, max(block_id+blocks-1) hwm
         from dba_extents
        group by file_id ) b
where a.file_id = b.file_id(+)
  and ceil( blocks*&&blksize/1024/1024) -
      ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) > 0
/

 =================
4) Schema management
 =================

--------------------------------------------
-- Count total rows in each tables in schema
--------------------------------------------
-- Identify the users, created after db creation
--
SELECT username,
       created
FROM   dba_users
WHERE  TO_DATE(TO_CHAR(created, 'ddmmyy'), 'ddmmyy') <> (SELECT TO_DATE(TO_CHAR(created, 'ddmmyy'), 'ddmmyy')
                                                         FROM   v$database)
/

-- Count number of rows in Each Table (User Wise)
-- Run in SYS Schema
--
SELECT   owner,
         table_name,
         To_number(Extractvalue(Xmltype(dbms_xmlgen.Getxml('select count(*) c from '
                                                           ||owner
                                                           ||'.'
                                                           ||table_name)),'/ROWSET/ROW/C')) COUNT
FROM     dba_tables
WHERE    owner = Nvl(Upper('&owner'),owner)
         AND owner NOT IN ('PERFSTAT','TSMSYS','BI','PM','MDDATA','IX','SH','DIP','OE','DBSNMP','SYSMAN','MDSYS',
                           'ORDSYS','EXFSYS','DMSYS','WMSYS','CTXSYS','ANONYMOUS','XDB','ORDPLUGI NS',
                           'SI_INFORMTN_SCHEMA','OLAPSYS','MGMT_VIEW','SYS','SYSTEM','OUTLN')
ORDER BY 1
/
-- Query 2
--
SELECT
 table_name,
 TO_NUMBER(extractvalue(XMLTYPE(dbms_xmlgen.getxml('select count(*) c from '||owner||'.'||table_name)),'/ROWSET/ROW/C')) COUNT
FROM DBA_TABLES
where owner=NVL(UPPER(TRIM('&owner')),ora_login_user)
ORDER BY 1
/
---------------------------
-- Top-5 tables in a schema
---------------------------
SELECT *
FROM   (SELECT   SUBSTR(segment_name,0,30) "Segment name",
                 SUBSTR(segment_type,0,15) "Segment type",
                 SUM(bytes) / 1024 / 1024  "Mb"
            FROM dba_segments
           WHERE owner='PERFSTAT'
        GROUP BY segment_name, segment_type, owner
        ORDER BY 3 DESC)
WHERE  ROWNUM <= 5
/

 =========================
5) Object/Segment management
 =========================
------------------------
-- To find dependencies:
------------------------
define obj_name = &object
SELECT name FROM dba_dependencies WHERE referenced_name = upper(trim('&&obj_name'))
UNION
SELECT referenced_name FROM dba_dependencies WHERE name = upper(trim('&&obj_name'))
/
undefine obj_name = &object
----------------------------
-- To find HWM in a segment:
----------------------------
SELECT BLOCKS
FROM   DBA_SEGMENTS
WHERE  OWNER=UPPER(owner) AND SEGMENT_NAME = UPPER(table)
/
ANALYZE TABLE owner.table ESTIMATE STATISTICS
/
SELECT EMPTY_BLOCKS
FROM   DBA_TABLES
WHERE  OWNER=UPPER(owner) AND TABLE_NAME = UPPER(table)
/
/*
Note:
-----
Calculation : Thus, the tables' HWM = (query result 1) - (query result 2) - 1
NOTE     : We can also use the DBMS_SPACE package and calculate the HWM = TOTAL_BLOCKS - UNUSED_BLOCKS - 1.
*/

 ===============================
6) How to manage block corruption:
 ===============================
------------------------------------------
-- To find the corrupted file and segment:
------------------------------------------
-- We can observe this error message in alert.log
-- Check the dbv log file for "Block Checking: DBA = , Block Type = KTB-managed data block"
--   Eg: Block Checking: DBA = 229422437, Block Type = KTB-managed data block
--
--
-- Gets the file number part of a data block address
select dbms_utility.data_block_address_file('') from dual ;
-- Eg:
-- select dbms_utility.data_block_address_file('229422437') from dual ;

-- Gets the datafile name
select name from v$datafile where file#=;
-- Gets the block number part of a data block address
select dbms_utility.data_block_address_block('') from dual ;
-- Eg:
-- select dbms_utility.data_block_address_block('229422437') from dual ;


-- Gets the corrupted schema,segment, segment type
set linesize 100;
column owner format a15;
column segment_name format a30;
column segment_type format a30;
SELECT owner, segment_name, segment_type
FROM   dba_extents
WHERE  file_id = &file_id
       AND &block_no BETWEEN block_id AND block_id + blocks - 1
/
-- Analyze segment
analyze . validate structure [cascade];
-- Eg:
-- analyze table SAPPF1.SWW_CONTOB validate structure;

--> Need to edit ************
SQL> select object_id from dba_objects where object_name='SWW_CONTOB' and owner='SAPPF1';
 OBJECT_ID
----------
     63835
SQL> select dbms_rowid.rowid_create(1,63835,54,2930021,0)min_rid,dbms_rowid.rowid_create(1,63835,54,2930021+1,0)max_rid from dual;
MIN_RID            MAX_RID
------------------ ------------------
AAAPlbAA2AALLVlAAA AAAPlbAA2AALLVmAAA
select count(*) cnt from SAPPF1.SWW_CONTOB where rowid between 'AAAPlbAA2AALLVlAAA' and 'AAAPlbAA2AALLVmAAA';
select count(*) cnt from SAPPF1.SWW_CONTOB where rowid between 'AAAPlbAA2AALLVlAAA' and 'AAAPlbAA2AALLVmAAA';

Link- http://forums.oracle.com/forums/thread.jspa?threadID=1052408&tstart=30
--< Need to edit ************

/*
----------
Example 1:
----------
SELECT segment_type, owner ||'.'||segment_name
FROM   dba_extents
WHERE  file_id = 9 AND 25759 BETWEEN block_id AND block_id + blocks - 1
/
----------
Example 2:
----------
SELECT owner, segment_name, segment_type
FROM   dba_extents
WHERE  file_id = 8 AND 82172 BETWEEN block_id AND block_id + blocks - 1
/
*/

 ====================
6) Backup and Recovery
 ====================
-------------------------------------------------------
Data movement from one site to another (Export-Import):
-------------------------------------------------------
nohup exp "'/ as sysdba'" file=.dmp log=.log full=y buffer=1000000 consistent=y statistics=none &
nohup imp '"/ as sysdba"' file=.dmp log=.log full=y commit=y buffer=1000000 ignore=y feedback=100000 &
@?/rdbms/admin/utlrp.sql
exec DBMS_STATS.GATHER_DATABASE_STATS (degree => 4,cascade => true ,estimate_percent => dbms_stats.auto_sample_size);

-------------
---------------
-- Watch Import
---------------
select substr(sql_text,instr(sql_text,'INTO "'),30)                                                     table_name,
       rows_processed,
       round((sysdate - to_date(first_load_time,'yyyy-mm-dd hh24:mi:ss')) * 24 * 60,
             1)          minutes,
       trunc(rows_processed / ((sysdate - to_date(first_load_time,'yyyy-mm-dd hh24:mi:ss')) * 24 * 60)) rows_per_min
from   sys.v_$sqlarea
where  sql_text like 'INSERT %INTO "%'
       and command_type = 2
       and open_versions > 0
/
Data pump:
----------
 Estimate dump size
 ------------------
 expdp "'/ as sysdba'" full=y estimate_only=y nologfile=y job_name=exp_dump_size
 expdp "'/ as sysdba'" schemas=scott estimate_only=y nologfile=y job_name=exp_dump_size       

---------------------------------
-- Monitor datapump Export/import
---------------------------------
select OWNER_NAME,JOB_NAME,OPERATION,STATE,JOB_MODE,ATTACHED_SESSIONS,DATAPUMP_SESSIONS from dba_datapump_jobs;
SELECT sid, serial#, context, sofar, totalwork,round(sofar/totalwork*100,2) "%_COMPLETE",time_remaining, elapsed_seconds FROM v$session_longops WHERE opname LIKE '%EXP%';

select sid,
       serial#
from   v$session s,
       dba_datapump_sessions d
where  s.saddr = d.saddr;
select sid,
       serial#,
       sofar,
       totalwork
from   v$session_longops;

Example for invoking expdp  using par file
------------------------------------------
File name = export_full_METADATA_ONLY_10042010.par
Content

directory=datapump_dir
dumpfile=exp_icustp_full_10042010_%U.dmp
filesize=4G
full=y
CONTENT=METADATA_ONLY
job_name=icustp_full_export
logfile=exp_icustp_full_10042010.log
status=300
parallel=8
Calling methode: nohup expdp / parfile=export_full_METADATA_ONLY_10042010.par &
-------------------------------------

Full db Export with nohup option -
 nohup exp "'/ as sysdba'" file=.dmp log=.log full=y rows=y indexes=y constraints=y grants=y buffer=1000000 &
 Example:
 --------
 nohup exp "'/ as sysdba'" file=exp_pac-mt_091009.dmp log=exp_pac-mt_091009.log owner=pac-mt direct=y buffer=1000000 consistent=y &

Checking log files After import -
 egrep "^IMP-^J^ORA-" imp_full_nncc_20090129.log| grep -v "already exists" | grep -v "compilation warnings"

Import:
-------
nohup imp '"/ as sysdba"' file=exp_sops4_091209.dmp log=imp_sops4_091209.log fromuser=sops4 touser=sops6 commit=y ignore=y &

Depending on the size of the export data we have to use pipe command to export with compress and split:
Example:
--------
1) mkdir for export:
 Here
2) Change directory to the EXPORT_DIR:

 cd
3) Remove previous pipe (if any):

 rm -f export_pipe

4) Make new pips (Compress):
 /usr/sbin/mknod mknod export_pipe p
 chmod 666 export_pipe

5) Start the Compress backgroud processes:             
 nohup cat export_pipe | gzip -9 > expdat.dmp.gz &
6) Finally, start the export to pipe:
 exp "'/ as sysdba'" file=export_pipe owner= consistent=y direct=y log=.log
7) Remove the pipe:
 rm -f export_pipe
Example:
--------
1)
orauis@s96uis01:/dump_2/exp/TT11236224 : /usr/sbin/mknod  /dump_2/exp/TT11236224/exp_pipe p
orauis@s96uis01:/dump_2/exp/TT11236224 : ls
exp_pipe
orauis@s96uis01:/dump_2/exp/TT11236224 : nohup gzip -c6 < /dump_2/exp/TT11236224/exp_pipe > export_uis.dmp.gz &
[1]     4309
orauis@s96uis01:/dump_2/exp/TT11236224 :  nohup exp edcadm/+ora4uss file=/dump_2/exp/TT11236224/exp_pipe full=y  direct=y log=export_uis.log  statistics=none consistent=yes  &
[2]     10972
orauis@s96uis01:/dump_2/exp/TT11236224 : Sending output to nohup.out
Sending output to nohup.out
orauis@s96uis01:/dump_2/exp/TT11236224 : ls
exp_pipe           export_uis.dmp.gz  export_uis.log     nohup.out

2)

make pipe -
 ora_qda8@s96qdap4:/oracle/data/TT9967439 : /usr/sbin/mknod  /oracle/data/TT9967439/exp_pipe p 
define gzip of dump file -

 ora_qda8@s96qdap4:/oracle/data1/TT9967439 : nohup gzip -c6 < /oracle/data/TT9967439/exp_pipe > export_pac-mt..dmp.gz &
export command -
 ora_qda8@s96qdap4:/oracle/data1/TT9967439 :  nohup exp "'/ as sysdba'" file=/oracle/data/TT9967439/exp_pipe owner= PAC-MT consistent=y direct=y log=export_pac-mt.log &

---> ref link: http://www.idevelopment.info/data/Oracle/DBA_tips/Export_Import/EXP_2.shtml

DB level export:
----------------
nohup exp "'/ as sysdba'" file = WFS_280110.dmp log = WFS_280110.log full=y rows=y buffer=1000000 &

Schema level export/import:
---------------------------
nohup exp "'/ as sysdba'" file=exp_sops4_091209.dmp log=exp_sops4_091209.log owner=sops4 direct=y buffer=1000000 consistent=y &
nohup imp '"/ as sysdba"' file=exp_sops4_091209.dmp log=imp_sops4_091209.log fromuser=sops4 touser=sops6 commit=y ignore=y &
nohup imp '"/ as sysdba"' file=leadp_full_201002010200.dmp log=imp_leadp_full_201002010200.log fromuser=EDISON touser=PROTOKOLL tables=TBLLEADSESSIONS_2009,TBLCPMSPROTOKOLL_2009,TBLLEADPROTOKOLL_2009_PART1,TBLLEADPROTOKOLL_2009_1 commit=y ignore=y buffer=1000000 &

Note:
-----
User the command to copy the schema-
 set long 100000
 select dbms_metadata.get_ddl('USER','SOPS6') user_ddl from dual;

7)  ==================
 Process managemant
 ==================
-- List the number of user sessions , OS processes that has been idle
-- from the past 12 Hrs.except Background processes.
--
SELECT s.SID "Sid", s.serial# "Serial#", p.spid " OS Process", s.osuser " OS User"
     , s.program "Program", s.logon_time "Log on time",last_call_et "Last call"
  FROM v$process p, v$session s
 WHERE p.addr = s.paddr
   AND s.status = 'INACTIVE'
   AND s.username IS NOT NULL
   AND p.background IS NULL
   AND ROUND (s.last_call_et / 3600, 2) > 12
/

-------------------------------------------------------------
-- How to kill oracle session and corresponding OS process -
-------------------------------------------------------------
-- Run the SQLs in the following order
-- 1)
SELECT p.spid, s.sid, s.serial#
FROM v$session s, v$process p
WHERE s.paddr = p.addr
AND s.type='USER'
AND s.username= NVL(UPPER(TRIM('&user')),s.username);
-- 2)

SELECT 'ALTER SYSTEM KILL SESSION '''||s.sid||','||s.serial#||''' IMMEDIATE;'
FROM v$session s, v$process p
WHERE s.paddr = p.addr
AND s.type='USER'
AND s.username= NVL(UPPER(TRIM('&user')),s.username);
-- alter system kill session '39,44214' immediate;

-- 3)

SELECT 'kill -9 '||p.spid os_cmd
FROM v$session s, v$process p
WHERE s.paddr = p.addr
AND s.type='USER'
AND s.username= NVL(UPPER(TRIM('&user')),s.username);

=================================================
-- EDCADM/Keypass-Y:\05_DB_TEAM S/w pwd: +ora4uss
=================================================
Scripting in oracle
===================
for i in audit_e cognos82 cognos8e crne crni dwhgse pcrepoe pcrepoi pcrepou dwhxas_e
do
export ORACLE_SID=$i
echo $ORACLE_SID@`hostname`
echo '-----------------------'
echo "select count(*) from v\$session;"| sqlplus "/ as sysdba"
echo "select count(username) from dba_users;"| sqlplus "/ as sysdba"
done

for i in hraap9fg hrepbas9 hrepdev9 hrepdmo9 hrepfg9 hrepint9 hrepipw9 hrepmiga hrepmod9 hrepmst9 hrepply9 hrepupg9 hrwt9dm2 upkit
        do
        export ORACLE_SID=$i
        sqlplus -S "/ as sysdba" @$ORACLE_HOME/rdbms/admin/utlrp.sql
        done

script for User creation in icust
=================================

for i in
do
echo "--------------- $i ---------------" >> icust_user_cre_.log
sqlplus /nolog @mic_create_user_dcag.sql edcadm icustp $i $i MIC_APP_ALLG
echo "select count(*) from MIC_CCS_WAEPOS;"|sqlplus -S $i/$i >> icust_user_cre.log
echo "----------------------------------" >> cust_user_cre_.log
done


Example:
--------
for i in  ANDMEIE BSTROBU XV12K1S YVOORWO MANKOCK DAJESS DGEWERT MBAJIC AMILSKI MLAMBER HESCHM1 TISIMON MARGFIS MEDENZL JKOLLEW JULIA7S
do
echo "--------------- $i ---------------" >> icust_user_cre_.log
sqlplus /nolog @mic_create_user_dcag.sql edcadm XXXX icustp $i $i MIC_APP_ALLG
echo "select count(*) from MIC_CCS_WAEPOS;"|sqlplus -S $i/$i >> icust_user_cre.log
echo "----------------------------------" >> cust_user_cre_.log
done
==============
Typical Errors
==============
ORA-00119: invalid specification for system parameter LOCAL_LISTENER
ORA-00132: syntax error or unresolved network name 'LISTENER_ORCL2'
Check : http://www.dbasupport.com/forums/archive/index.php/t-56974.html

oracle@s96gssi5z1:/home/oracle :  for i in spas asrapubl tic aps cas ppt repa sac tic ticon
 do
 export ORACLE_SID=$i
 sqlplus "/ as sysdba" < select * from v\$instance;
 exit
 ;
 EOF
 done


=======================================
RMAN
=====
Trouble shooting RMAN (10g) - http://cs.scu.edu.cn/~zuojie/oracle/server.101/b10734/rcmtroub.htm
Links
=====
http://www.orafaq.com/wiki/Oracle_database_FAQ

To add (Verify and Add)
=======================

Rename a tablespace
-------------------
ALTER TABLESPACE ts1 RENAME TO ts2;
However, you must adhere to the following restrictions:
    * COMPATIBILITY must be set to at least 10.0.1
    * Cannot rename SYSTEM or SYSAUX
    * Cannot rename an offline tablespace
    * Cannot rename a tablespace that contains offline datafiles
For older releases, use the following workaround:
    * Export all of the objects from the tablespace
    * Drop the tablespace including contents
    * Recreate the tablespace
    * Import the objects
To find used/free space in a TEMPORARY tablespace
-------------------------------------------------
Unlike normal tablespaces, true  temporary tablespace information is  not listed
in DBA_FREE_SPACE. Instead use the V$TEMP_SPACE_HEADER view:
SELECT tablespace_name, SUM(bytes_used), SUM(bytes_free)
FROM   V$temp_space_header
GROUP  BY tablespace_name;
To report true free space within the used portion of the TEMPFILE:
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;
To know used space of temp tablespace:
-------------------------------------------------
SELECT property_value
  2  FROM   database_properties
WHERE  property_name = 'DEFAULT_TEMP_TABLESPACE'

SELECT used_percent
 FROM   dba_tablespace_usage_metrics
 WHERE  tablespace_name=
(SELECT property_value
   FROM database_properties
WHERE   property_name = 'DEFAULT_TEMP_TABLESPACE')
/
To monitor who is using a temporary segment
-------------------------------------------
1) For every user using temporary space, there is an entry in SYS.V$_LOCK with type
   'TS'.
2) All temporary segments are named 'ffff.bbbb'  where 'ffff' is the file it  is in
   and 'bbbb' is first block of the segment.
  
3) If your  temporary tablespace  is set  to TEMPORARY,  all sorts  are done in one
   large temporary segment. For usage stats, see SYS.V_$SORT_SEGMENT
From Oracle 8, one can just query SYS.v$sort_usage. Look at these examples:
select s.username, u."USER", u.tablespace, u.contents, u.extents, u.blocks
from   sys.v_$session s, sys.v_$sort_usage u
where  s.saddr = u.session_addr
/
select s.osuser, s.process, s.username, s.serial#,
       sum(u.blocks)*vp.value/1024 sort_size
from   sys.v_$session s, sys.v_$sort_usage u, sys.v_$parameter vp
where  s.saddr = u.session_addr
  and  vp.name = 'db_block_size'
  and  s.osuser like '&1'
group  by s.osuser, s.process, s.username, s.serial#, vp.value
/

To monitor who all are using which UNDO or TEMP segment
-------------------------------------------------------
Execute the following query to determine who is using a particular UNDO or Rollback Segment:
SELECT  TO_CHAR(s.sid)||','||TO_CHAR(s.serial#) sid_serial,
 NVL(s.username, 'None') orauser,
 s.program,r.name undoseg,t.used_ublk * TO_NUMBER(x.value)/1024||'K' "Undo"
FROM sys.v_$rollname r,sys.v_$session s,sys.v_$transaction t,sys.v_$parameter x
WHERE s.taddr = t.addr
  AND r.usn   = t.xidusn(+)
  AND x.name  = 'db_block_size'
/

SID_SERIAL ORAUSER    PROGRAM                        UNDOSEG         Undo
---------- ---------- ------------------------------ --------------- -------
260,7      SCOTT      sqlplus@localhost.localdomain  _SYSSMU4$       8K
                      (TNS V1-V3)
Execute the following query to determine who is using a TEMP Segment:
SELECT  b.tablespace,
 ROUND(((b.blocks*p.value)/1024/1024),2)||'M' "SIZE",
 a.sid||','||a.serial# SID_SERIAL,
 a.username,
 a.program
FROM sys.v_$session a,sys.v_$sort_usage b,sys.v_$parameter p
WHERE p.name  = 'db_block_size'
  AND a.saddr = b.session_addr
ORDER BY b.tablespace, b.blocks
/

TABLESPACE SIZE    SID_SERIAL USERNAME PROGRAM
---------- ------- ---------- -------- ------------------------------
TEMP       24M     260,7      SCOTT    sqlplus@localhost.localdomain
                                       (TNS V1-V3)

To get the view definition of fixed views/tables
------------------------------------------------
Query v$fixed_view_definition. Example:
SELECT * FROM v$fixed_view_definition WHERE view_name='V$SESSION';

To monitor the fill level of current redo log file
--------------------------------------------------
Here is a query that can tell you how full the current redo log file is.
Handy for when you need to predict when the next log file will be archived out.

SELECT  le.leseq                  "Current log sequence No",
 100*cp.cpodr_bno/le.lesiz "Percent Full",
 cp.cpodr_bno              "Current Block No",
 le.lesiz                  "Size of Log in Blocks"
FROM x$kcccp cp, x$kccle le
WHERE le.leseq =CP.cpodr_seq
AND bitand(le.leflg,24) = 8
/

Current log sequence No Percent Full Current Block No Size of Log in Blocks
----------------------- ------------ ---------------- ---------------------
                    416   48.6669922            49835                102400

or
Finding how much percentage  of current redo log  is filled is bit  tricky since
the information is not  exposed in any V$  views. We have to  directly query the
X$tables to get that information. The X$views we use here are x$kccle (Kernel
Cache ControlfileComponent Log file Entry) and x$kcccp (Kernel Cache Checkpoint Progress).

select  le.leseq                               current_log_sequence#,
        100 * cp.cpodr_bno / le.lesiz          percentage_full
from    x$kcccp cp, x$kccle le
where le.leseq =cp.cpodr_seq
and     le.ledup != 0
/

Setting alias for sqlplus '/as sysdba' in OS level
--------------------------------------------------
If you are tired  of typing [i]sqlplus "/as  sysdba"[/i] every time you  want to
perform some DBA task, implement the following shortcut:
On Unix/Linux systems:
Add the following alias to your .profile or .bash_profile file:
alias sss='sqlplus "/as sysdba"'
On Windows systems:
Create a batch file, sss.bat, add the  command to it, and place it somewhere  in
your PATH. Whenever you now want to start sqlplus as sysdba, just type "sss".
Much less typing for ya lazy DBA's.
Note: From Oracle 10g you don't need to put the "/AS SYSDBA" in quotes anymore.

To check what all are the patches are installed in Oracle Home
--------------------------------------------------------------
DBA's  often  do  not  document  the patches  they  install.  This  may  lead to
situations where a feature  works on machine X,  but not on machine  Y. This FAQ
will show how you can list and compare the patches installed within your  Oracle
Homes.
All patches that  are installed with  Oracle's OPatch Utility  (Oracle's Interim
Patch Installer) can be listed by invoking the opatch command with the lsinventory
option. Here is an example:
$ cd $ORACLE_HOME/OPatch
$ opatch lsinventory
Invoking OPatch 10.2.0.1.0
Oracle interim Patch Installer version 10.2.0.1.0
Copyright (c) 2005, Oracle Corporation.  All rights reserved..
...
Installed Top-level Products (1):
Oracle Database 10g                                           10.2.0.1.0
There are 1 products installed in this Oracle Home.
There are no Interim patches installed in this Oracle Home.
OPatch succeeded.
NOTE: If OPatch is not installed into your Oracle Home ($ORACLE_HOME/OPatch), you may need to download it from Metalink and install it yourself.

How does one give developers access to trace files (required as input to tkprof)
--------------------------------------------------------------------------------
The  alter  session  set   sql_trace=true  command  generates  trace   files  in
USER_DUMP_DEST that can be  used by developers as  input to tkprof. On  Unix the
default file mask for these files are "rwx r-- ---".
There is an undocumented INIT.ORA parameter that will allow everyone to read
(rwx r-- r--) these trace files:
_trace_files_public = true
Include this in your INIT.ORA file and bounce your database for it to take effect.

Oracle SYSDATE and calculating time
===================================
One of the confounding problems with Oracle DATE datatypes is the computation of
elapsed time. Oracle SYSDATE  functions can be used  to convert an elapsed  time
into rounded elapsed minutes, and place the value inside an Oracle table.
SQL> select sysdate-(sysdate-3) from dual;
SYSDATE-(SYSDATE-3)
-------------------
                  3
Here we see  that elapsed times  are expressed in  days. Hence, we  can use easy
conversion  functions to  convert this  to hours  or minutes:However,  when the
minutes are not a whole number, we have the problem of trailing decimal places:
select (sysdate-(sysdate-3.111))*1440 from dual;

(SYSDATE-(SYSDATE-3.111))*1440
------------------------------
                    4479.83333
Of course, we  can overcome this  with the ROUND  function with Oracle  SYSDATE,
remembering that we must first convert the DATE datatype to a NUMBER type:
select round(to_number(sysdate-(sysdate-3.111))*1440) from dual;
ROUND(TO_NUMBER(SYSDATE-(SYSDATE-3.111))*1440)
----------------------------------------------
                                          4480

SQLs to view OS process and Oracle session info
===============================================
-- This script provides information on active SQL. (This was built for use on Oracle9i Database.)
--
SELECT s.sid, s.status, s.process, s.osuser, a.sql_text, p.program
  FROM   v$session s, v$sqlarea a, v$process p
 WHERE  s.sql_hash_value = a.hash_value
   AND s.sql_address = a.address
   AND s.paddr = p.addr
   AND s.schemaname = '&user'
   AND s.sid=&sid
   AND s.serial#=&serial
   AND s.status = 'ACTIVE'
/

Use this commands and sql query to show information about OS process and Oracle user session.
Useful if for example you notice a single process is chewing up CPU on the server.
At the Unix prompt (replace 22910 with the actual process id):
$ ps -ef | grep 22910
oracle 22910     1 14 09:16:59 ?       32:09 oracleDBNAME
(DESCRIPTION=(LOCAL=no)(ADDRESS=(PROTOCOL=BEQ)))
In sqlplus or TOAD run this query:
SELECT s.saddr, s.sid, s.serial#, s.username,
 s.osuser, s.machine, s.program, s.logon_time, s.status,
 p.program, p.spid
FROM v$session s, v$process p
WHERE s.paddr = p.addr
AND p.spid IN (22910);
If otherwise you need to identify Unix process for a specific Oracle database session run SQL
statement below (assuming SIDs are 39 and 24, can also put username or osuser etc in whe where
clause):
SELECT p.program, p.spid, s.saddr, s.sid, s.serial#, s.username,
 s.osuser, s.machine, s.program, s.logon_time, s.status
FROM v$session s, v$process p
WHERE s.paddr = p.addr
AND s.sid IN (39, 24);
PROGRAM                        SPID
------------------------------ ---------   ...
oracle@hostname (TNS V1-V3)    590         ...
oracle@hostname (TNS V1-V3)    6190        ...
At the OS prompt get the process information
ps -ef | egrep '590|6190'
  oracle 18232 14573  0 10:16:17 pts/4    0:00 egrep 590|6190
  oracle  6190     1  0   Jul 28 ?       14:40 oracleDBNAME
(DESCRIPTION=(LOCAL=no)(ADDRESS=(PROTOCOL=BEQ)))
  oracle   590     1  0   Jul 30 ?       12:10 oracleDBNAME
(DESCRIPTION=(LOCAL=no)(ADDRESS=(PROTOCOL=BEQ)))

-- SQL to view SQL text for user session
-- Replace DB_USER with the actuall database username and os_user with the OS username.
select a.sql_text, b.username, b.osuser, b.logon_time, b.program,b.machine, b.sid, b.serial#
from v$sql a, v$session b
where a.address = b.sql_address
and b.username = 'SYS'
and b.osuser = 'os_user';

Statistics
==========
Gather statistics example:
begin
dbms_stats.gather_table_stats (ownname => 'MICAPP',tabname => 'MIC_EINKOP',partname => null,estimate_percent => NULL,block_sample => false,method_opt => 'FOR ALL INDEXED COLUMNS SIZE AUTO',degree => 4,granularity => 'ALL',cascade => true);
end;
/

SR update templet
=================
Hello,
Thank you for your patience.
Please keep this session active for few more days.
We are still waiting for the feedback from customer.
Regards,
EDC_Admin
To Check
========
Note 352907.1:Script To Run DBV On All Datafiles Of the Database
+ Please review Instance memory parameter & try to accomodate all oracle SGA in physical memory.
+ Refer following metalink note for memory related parameter on AIX.
Note 316533.1 AIX: Database performance gets slower the longer the database is running
Swap Activities
Using: lsps -a
Page Space Physical Volume Volume Group Size %Used Active Auto Type
hd6 hdisk1 rootvg 12288MB 25 yes yes lv
==============================================
------------------------------------------------
-- Extracting the active SQL a user is executing
------------------------------------------------
SELECT sesion.sid,
       sesion.username,
       optimizer_mode,
       hash_value,
       address,
       cpu_time,
       elapsed_time,
       sql_text
FROM   v$sqlarea sqlarea,
       v$session sesion
WHERE  sesion.sql_hash_value = sqlarea.hash_value
       AND sesion.sql_address = sqlarea.address
       AND sesion.username IS NOT NULL
       AND sesion.sid = &sid AND sesion.serial# = &serial      
----------------------------------------
-- Find most active SQL in the last hour
----------------------------------------
1)
SELECT   session_id,
         session_serial#,
         sql_id,
         COUNT(* ),
         ROUND(COUNT(* ) / SUM(COUNT(* ))
                             OVER(),2) pctload
FROM     gv$active_session_history
WHERE    sample_time > SYSDATE - 1 / 24
         AND session_type = 'BACKGROUND'
GROUP BY sql_id,
         session_id,
         session_serial#
ORDER BY COUNT(* ) DESC;
2)
SELECT   session_id,
         session_serial#,
         sql_id,
         COUNT(* ),
         ROUND(COUNT(* ) / SUM(COUNT(* ))
                             OVER(),2) pctload
FROM     gv$active_session_history
WHERE    sample_time > SYSDATE - 1 / 24
         AND session_type = 'FOREGROUND'
GROUP BY sql_id,
         session_id,
         session_serial#
ORDER BY COUNT(* ) DESC;
--------------------------------------------------
-- To find the scheduled jobs using dbms_scheduler
--------------------------------------------------
SELECT job_name,
       failure_count,
       To_char(start_date,'dd-mm-yy hh:mi:ss') start_date,
       repeat_interval,
       job_action
FROM   dba_scheduler_jobs
WHERE  job_name = (SELECT object_name
                   FROM   dba_objects
                   WHERE  object_id = 1678766);
-- Ref: http://forums.oracle.com/forums/thread.jspa?threadID=651890
-- Ref: http://www.oradev.com/dbms_scheduler.jsp

--------------------------------------------------------
-- To find all the privileges granted for a user in db:
--------------------------------------------------------
SET serveroutput on;
execute DBMS_OUTPUT.ENABLE (1000000);
BEGIN
  ---------------------
  -- system privileges:
  ---------------------
  dbms_output.PUT_LINE(RPAD('System privileges',30,' ')); 
  dbms_output.PUT_LINE(RPAD('=',30,'=')); 
  FOR i IN (SELECT privilege
            FROM   dba_sys_privs
            WHERE  grantee = 'TESTER')
  LOOP
    dbms_output.PUT_LINE(RPAD(i.privilege,30,' '));
  END LOOP; 
  dbms_output.PUT_LINE(CHR(10)); 
  --------------------
  -- Table privileges:
  --------------------
  dbms_output.PUT_LINE(RPAD('Object privileges',30,' ')); 
  dbms_output.PUT_LINE(RPAD('=',30,'=')); 
  dbms_output.PUT_LINE(RPAD('OWNER',15,' ')||CHR(32)||RPAD('TABLE NAME',30,' ')||CHR(32)||RPAD('PRIVILEGE',30,' ')); 
  dbms_output.PUT_LINE(RPAD('-',15,'-')||CHR(32)||RPAD('-',30,'-')||CHR(32)||RPAD('-',30,'-')); 
  FOR i IN (SELECT owner,
                   table_name,
                   privilege
            FROM   dba_tab_privs
            WHERE  grantee = 'TESTER')
  LOOP
    dbms_output.PUT_LINE(RPAD(i.owner,15,' ')||CHR(32)||RPAD(i.table_name,30,' ')||CHR(32)||RPAD(i.privilege,30,' '));
  END LOOP; 
  dbms_output.PUT_LINE(CHR(10)); 
  --------------------
  -- Role privileges:
  --------------------
  dbms_output.PUT_LINE(RPAD('Roles granted',30,' ')); 
  dbms_output.PUT_LINE(RPAD('=',30,'=')); 
  FOR i IN (SELECT granted_role
            FROM   dba_role_privs
            WHERE  grantee = 'TESTER')
  LOOP
    dbms_output.PUT_LINE(RPAD(i.granted_role,30,' '));
  END LOOP;
END;
/

-----------
Dependency:
-----------
col REFERENCED_NAME format a20
col REFERENCED_TYPE format a15
SELECT NAME,
       TYPE,
       referenced_name,
       referenced_type
FROM   dba_dependencies
WHERE  NAME = 'PROC_GET_DB_SIZE'
        OR referenced_name = 'PROC_GET_DB_SIZE'
UNION
SELECT NAME,
       TYPE,
       referenced_name,
       referenced_type
FROM   dba_dependencies
WHERE  NAME = 'GET_DB_SIZE'
        OR referenced_name = 'GET_DB_SIZE';
col object_name format a20
col object_type format a15
SELECT object_name,
       status
FROM   dba_objects
WHERE  object_name IN ('PROC_GET_DB_SIZE','GET_DB_SIZE');

-----------------------------------
-- Checking the background process:
-----------------------------------
SELECT COUNT(* ) FROM   v$process WHERE  background = 1
/
SELECT program FROM   v$process WHERE  background = 1
/

---------------------------------------------------------------------------
-- Checking archive log history/log switch history (time of archive, etc:):
---------------------------------------------------------------------------
SELECT sequence#                                 seq,
       TO_CHAR(first_time,'dd-mm-yy hh24:mi:ss') archived_on
FROM   v$log_history
WHERE  first_time > TRUNC(SYSDATE) - 1
/

SELECT sequence#                                 seq,
       TO_CHAR(first_time,'dd-mm-yy hh24:mi:ss') archived_on
FROM   v$log_history
WHERE  first_time > TRUNC(SYSDATE) - 1;

set lines 120;
set pages 999;
SELECT * FROM (
SELECT   TO_CHAR(FIRST_TIME, 'DD/MM') AS "DAY"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '00', 1, 0)), '99') "00"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '01', 1, 0)), '99') "01"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '02', 1, 0)), '99') "02"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '03', 1, 0)), '99') "03"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '04', 1, 0)), '99') "04"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '05', 1, 0)), '99') "05"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '06', 1, 0)), '99') "06"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '07', 1, 0)), '99') "07"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '08', 1, 0)), '99') "08"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '09', 1, 0)), '99') "09"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '10', 1, 0)), '99') "10"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '11', 1, 0)), '99') "11"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '12', 1, 0)), '99') "12"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '13', 1, 0)), '99') "13"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '14', 1, 0)), '99') "14"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '15', 1, 0)), '99') "15"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '16', 1, 0)), '99') "16"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '17', 1, 0)), '99') "17"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '18', 1, 0)), '99') "18"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '19', 1, 0)), '99') "19"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '20', 1, 0)), '99') "20"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '21', 1, 0)), '99') "21"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '22', 1, 0)), '99') "22"
       , TO_NUMBER(SUM(DECODE(TO_CHAR(FIRST_TIME, 'HH24'), '23', 1, 0)), '99') "23"
    FROM V$LOG_HISTORY
    WHERE extract(year FROM FIRST_TIME) = extract(year FROM sysdate)
 GROUP BY TO_CHAR(FIRST_TIME, 'DD/MM')
 ORDER BY TO_DATE(extract(year FROM sysdate) || DAY, 'YYYY DD/MM') DESC
) WHERE ROWNUM < 8
/
**** !!! Need to check !!! ****

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

------------------------------------
-- To find tablespace creation time:
------------------------------------
SELECT   a.ts#,
         a.name tbsname,
         TO_CHAR(MIN(b.creation_time),'dd-mm-yy hh24:mi:ss') created
FROM     v$tablespace a,
         v$datafile b
WHERE    a.ts# = b.ts#
GROUP BY a.name,
         a.ts#
ORDER BY a.ts#
/
------------------------------------------------------
- To find tablespaces created after database creation:
------------------------------------------------------

SELECT   p.tbs#,
         p.tbsname,
         TO_CHAR(p.created,'dd-mm-yyyy') created
FROM     (SELECT   a.ts#               tbs#,
                   a.name              tbsname,
                   TO_DATE(TO_CHAR(MIN(b.creation_time),'dd-mm-yy'),
                           'dd-mm-yy') created
          FROM     v$tablespace a,
                   v$datafile b,
                   v$database c
          WHERE    a.ts# = b.ts#
          GROUP BY a.name,
                   a.ts#
          ORDER BY a.ts#) p,
         (SELECT TO_DATE(TO_CHAR(created,'dd-mm-yy'),'dd-mm-yy') created
          FROM   v$database) q
WHERE    p.created > q.created
ORDER BY p.created
/
------------------------------------------
- Datafiles added after database creation:
------------------------------------------

SELECT   a.file#,
         a.name,
         TO_CHAR(a.creation_time,'dd-mm-yyyy') created
FROM     v$datafile a,
         v$database b
WHERE    TO_DATE(TO_CHAR(a.creation_time,'dd-mm-yy'),'dd-mm-yy') > TO_DATE(TO_CHAR(b.created,'dd-mm-yy'),'dd-mm-yy')
ORDER BY TO_DATE(TO_CHAR(a.creation_time,'dd-mm-yy'),'dd-mm-yy')
/

-- With database creation date

SELECT   DECODE(ROWNUM,1,TO_CHAR(b.created,'dd-mm-yy'),
                       NULL) dbcreated,
         a.file#,
         a.name,
         TO_CHAR(a.creation_time,'dd-mm-yyyy') filecreated
FROM     v$datafile a,
         v$database b
WHERE    TO_DATE(TO_CHAR(a.creation_time,'dd-mm-yy'),'dd-mm-yy') > TO_DATE(TO_CHAR(b.created,'dd-mm-yy'),'dd-mm-yy')
ORDER BY TO_DATE(TO_CHAR(a.creation_time,'dd-mm-yy'),'dd-mm-yy')
/
----------------------------------------------
-- List users created after database creation:
----------------------------------------------

SELECT username,
       TO_CHAR(created,'dd-mm-yy hh24:mi:ss') created
FROM   dba_users
WHERE  TO_DATE(TO_CHAR(created,'dd-mm-yy'),'dd-mm-yy') > (SELECT TO_DATE(TO_CHAR(created,'dd-mm-yy'),'dd-mm-yy')
                                                          FROM   v$database);
---------------------------------------------
-- List users created with database creation:
---------------------------------------------
SELECT username
FROM   dba_users
WHERE  username NOT IN (SELECT username
                        FROM   dba_users
                        WHERE  TO_DATE(TO_CHAR(created,'dd-mm-yy'),'dd-mm-yy') > (SELECT TO_DATE(TO_CHAR(created,'dd-mm-yy'),'dd-mm-yy')
                                                                                  FROM   v$database));
--------------------------------------------------------------------
-- In UNIX environment, fetch processed rows in long running query
--------------------------------------------------------------------
-- 1) Find spid / pid from OS
-- 2) Issue the below command
SELECT rows_processed
FROM   v$sql
WHERE  hash_value = (SELECT sql_hash_value
                     FROM   v$session
                     WHERE  paddr = (SELECT addr
                                     FROM   v$process
                                     WHERE  spid = '&spid'));

---------------------------------
-- How to Relink oracle binaries:
---------------------------------
1) login to oracle user and Find oracle homes
 echo $ORACLE_HOME
2) cd $ORACLE_HOME/bin
3) Apply relink with option all
 relink all
** Other parameters: all, oracle, network, client, client_sharedlib, interMedia,ctx, precomp, utilities, oemagent, ldap

-----------------------
-- Purge listener log :
------------------------
 > fuser *

 > lsnrctl set log_status off

 > mv listener.log listener.log.$(date +"%d%m%Y")
 > lsnrctl set log_status on

--------------------------
-- Locking and find locks:
--------------------------
col "Object" format a20
set numwidth 12
set lines 132
set pages 50
@title132 'Object Wait Statistics'
spool rep_out\&&db\obj_stat_xtab
SELECT *
FROM   (SELECT   DECODE(GROUPING(a.object_name),1,'All Objects',
                                                a.object_name) AS "Object",
                 SUM(CASE
                       WHEN a.statistic_name = 'ITL Waits'
                       THEN a.VALUE
                       ELSE NULL
                     END) "ITL Waits",
                 SUM(CASE
                       WHEN a.statistic_name = 'buffer busy waits'
                       THEN a.VALUE
                       ELSE NULL
                     END) "Buffer Busy Waits",
                 SUM(CASE
                       WHEN a.statistic_name = 'row lock waits'
                       THEN a.VALUE
                       ELSE NULL
                     END) "Row Lock Waits",
                 SUM(CASE
                       WHEN a.statistic_name = 'physical reads'
                       THEN a.VALUE
                       ELSE NULL
                     END) "Physical Reads",
                 SUM(CASE
                       WHEN a.statistic_name = 'logical reads'
                       THEN a.VALUE
                       ELSE NULL
                     END) "Logical Reads"
        FROM     v$segment_statistics a
        WHERE    a.owner LIKE UPPER('&owner')
        GROUP BY ROLLUP(a.object_name)) b
WHERE  (b."ITL Waits" > 0
         OR b."Buffer Busy Waits" > 0);

========================================
-- Command to print 2 consicutive lines:
========================================
select 'ALTER TABLE '||owner||'.'||table_name||' ENABLE ROW MOVEMENT;'||chr(10)||'ALTER TABLE '||owner||'.'||table_name||' SHRINK SPACE CASCADE;' from dba_tables where tablespace_name in ('CBFC_E_DATA','CBFC_E_INDEX') and owner='KINTANA';

================================================
Files to be backed up for OFFLINE/ONLINE backup:
================================================
Offline Backup:
---------------
Generate the list of DB files for the backup ( Datafiles, online redolog  files,
controlfile trace backup, controlfiles, init parameter file, password file)
Shutdown the database

SELECT SUBSTR(host_name,0,10) host_name, instance_name, status,TO_CHAR(startup_time,'dd-mm-yy hh24:mi:ss') startup_time
FROM   v$instance
/
SELECT name, dbid, open_mode, log_mode, force_logging
FROM   v$database
/
SELECT name
FROM   v$controlfile
/
SELECT name
FROM   v$datafile
/
SELECT member
FROM   v$logfile
/
ALTER database backup controlfile TO trace
/

pfile;

Online Backup:
--------------
Generate the filelist  for backup (  Data files, controlfile,  controlfile trace
backup,  init parameter  file, password  file) Determine  the range  of  offline
redologs necessary for a first consistency  recovery for the backup by  checking
the alert.log  (Generate the  archived redo  log sequence  range by  identifying
“seq#” no. which was before the first “begin backup” statement and after the
last “end backup” statement in alert log file during that backup)

SELECT SUBSTR(host_name,0,10) host_name, instance_name, status,TO_CHAR(startup_time,'dd-mm-yy hh24:mi:ss') startup_time
FROM   v$instance
/
SELECT name, dbid, open_mode, log_mode, force_logging
FROM   v$database
/

SELECT name
FROM   v$datafile
/

ALTER database backup controlfile TO trace
/

pfile;

show parameter archive log list;


----------------- TEST for Object movement--------------------

> Check tablespaces and space availability
> select distinct segment_type from dba_segments where owner=UPPER(TRIM('&owner'));
> select sum(bytes)/1024/1024 mb from dba_segments where owner=UPPER(TRIM('&owner')) and segment_type in ('TABLE','INDEX');
> Create new tablespace with the minimum size of above output
> select tablespace_name,segment_type,count(segment_name) cnt from dba_segments where owner=UPPER(TRIM('&owner')) group by tablespace_name,segment_type;
> select 'ALTER TABLE '||owner||'.'||segment_name||' MOVE TABLESPACE '||tablespace_name||';' from dba_segments where owner=UPPER(TRIM('&owner')) and segment_type ='TABLE';
> select 'ALTER INDEX '||owner||'.'||segment_name||' REBUILD ONLINE TABLESPACE '||tablespace_name||';' from dba_segments where owner=UPPER(TRIM('&owner')) and segment_type ='INDEX';
>
http://decipherinfosys.wordpress.com/2007/09/05/moving-tables-to-a-different-tablespace-in-oracle/ - Moving objects
+++++++++++++++++++++++++++++++++++++++++++++++
How to find ORACLE_HOME from SQL prompt-
+++++++++++++++++++++++++++++++++++++++++++++++++
  select substr(file_spec,0,instr(file_spec,'/lib/libqsmashr.so' )) from DBA_LIBRARIES where library_name = 'DBMS_SUMADV_LIB' ;
+++++++++++++++++++++++++++++++++++++++++++++++++++
How to find Password file of database
++++++++++++++++++++++++++++++++++++++++++++++++++
SET pagesize 60 lines 1000 serveroutput ON feedback OFF;
EXECUTE dbms_output.ENABLE(1000000);
DECLARE
 v_orahome       varchar2(4000);
BEGIN
DBMS_SYSTEM.GET_ENV('ORACLE_HOME', v_orahome);
  DBMS_OUTPUT.PUT_LINE (CHR(10)||'(5). Password file:'
                            ||CHR(10)||'-------------------'||CHR(10)||v_orahome||'/dbs/orapw'||lower(trim(ora_database_name)));
       DBMS_OUTPUT.PUT_LINE (CHR(10));
END;
/
----------------------------
- How to use SLEEP function:
----------------------------
begin
for i in 1 ..10 loop
 dbms_backup_restore.sleep(30);
 dbms_output.put_line('Current time: '||to_char(sysdate,'mi:ss'));
 end loop;
end;
/

declare
 v_file utl_file.file_type;
begin
  for i in 1 ..10 loop
   dbms_backup_restore.sleep(1);
   v_file := utl_file.fopen (location   => 'EXPDP_DIR',
                              filename   => lower(trim(ora_database_name))|| to_char(sysdate, 'ddmmyyhhmiss')|| '.log',
                              open_mode          => 'a',
                                 max_linesize       => 32767
                            );
   utl_file.put_line (v_file, 'Current time: '||to_char(sysdate,'mi:ss'));
  end loop;
  utl_file.fclose (v_file);
exception
   when others then 
     utl_file.fclose (v_file);     
end;
/

Ref:
----
http://www.jlcomp.demon.co.uk/faq/sleep.html
http://www.chrispoole.co.uk/tips/plsqltip1.htm
------------------------
- For purging snapshots:
------------------------
-- Check snapcount in month wise
--
col snapdate format a8
select   to_char(snap_time,'Mon-yyyy') snapdate,
         count(snap_id)                snapcnt
from     perfstat.stats$snapshot
group by to_char(snap_time,'Mon-yyyy')
order by to_date(to_char(snap_time,'Mon-yyyy'),'Mon-yyyy')
/
-- Check begin snap and end snap from first n snaps
--
select snap_id
from (
select s.snap_id snap_id, rank() over (ORDER BY s.snap_id) snaprank
  from perfstat.stats$snapshot s
     , perfstat.stats$database_instance di
     , v$database d
     , v$instance i
 where s.dbid              = d.dbid
   and di.dbid             = d.dbid
   and s.instance_number   = i.instance_number  
   and di.instance_number  = i.instance_number  
   and di.startup_time     = s.startup_time
 order by snap_id
) where snaprank in (1,&no);

-- Check the snaps
select s.snap_id
     , to_char(s.snap_time,'dd-mm-yy hh24:mi:ss')    snap_date
  from perfstat.stats$snapshot s
     , perfstat.stats$database_instance di
     , v$database d
     , v$instance i
 where s.dbid              = d.dbid
   and di.dbid             = d.dbid
   and s.instance_number   = i.instance_number  
   and di.instance_number  = i.instance_number  
   and di.startup_time     = s.startup_time
 order by snap_id
/
-- Check Snap cout in month wise
--
break on report
compute sum of snap_cnt on report
select to_char(s.snap_time,'Mon-yyyy')    snap_month
     , min(s.snap_id) min_snapid
     , max(s.snap_id) max_snapid
     , count(s.snap_id) snap_cnt
  from perfstat.stats$snapshot s
     , perfstat.stats$database_instance di
     , v$database d
     , v$instance i
 where s.dbid              = d.dbid
   and di.dbid             = d.dbid
   and s.instance_number   = i.instance_number  
   and di.instance_number  = i.instance_number  
   and di.startup_time     = s.startup_time
 group by to_char(s.snap_time,'Mon-yyyy')
 order by to_date(to_char(s.snap_time,'Mon-yyyy'),'Mon-yyyy')
/
-- Check days cout for retention
--
select to_char(min(s.snap_time),'dd-Mon-yyyy')    begin_snap_date
     , to_char(max(s.snap_time),'dd-Mon-yyyy')    end_snap_date
     , max(s.snap_time)-min(s.snap_time)   days_retention
  from perfstat.stats$snapshot s
     , perfstat.stats$database_instance di
     , v$database d
     , v$instance i
 where s.dbid              = d.dbid
   and di.dbid             = d.dbid
   and s.instance_number   = i.instance_number  
   and di.instance_number  = i.instance_number  
   and di.startup_time     = s.startup_time
/

@?/rdbms/admin/sppurge;
-- Check Tablespace usage
--
SELECT   b.tablespace_name                              ,
         NVL(ROUND(SUM(a.bytes)   /1024/1024,2),0) mb   ,
         NVL(ROUND(SUM(a.maxbytes)/1024/1024,2),0) maxmb,
         NVL(ROUND(b.used_percent,2),0)            used_percent
FROM     dba_data_files a,
         dba_tablespace_usage_metrics b
WHERE    a.tablespace_name=b.tablespace_name
AND  b.tablespace_name in ((SELECT UPPER(value) FROM v$parameter WHERE name ='undo_tablespace'),
          (SELECT default_tablespace FROM dba_users WHERE username='PERFSTAT'))
GROUP BY b.tablespace_name,
         b.used_percent
ORDER BY used_percent DESC
/
select object_name,object_type from dba_objects where owner ='PERFSTAT' and status <> 'VALID';
UTL_RECOMP
EXECUTE UTL_RECOMP.RECOMP_SERIAL('SCOTT');
exec dbms_utility.compile_schema(schema=>'PERFSTAT',compile_all=>false);
Ref:
-----
http://www.oracle.com/technology/oramag/oracle/06-may/o36plsql.html
http://www.oracle-database-tips.com/compile_oracle_schema.html

--------------------------------------------------------
-- SQL to generate script for compiling invalid objects:
--------------------------------------------------------
set heading off linesize 100
spool compileinvalidobjs.sql
select decode (object_type, 'SYNONYM','alter public '
              ||lower(object_type)
              ||' '
              ||lower(object_name)
              ||' compile;' , 'PACKAGE BODY','alter package '
              ||' '
              ||lower(owner)
              ||'.'
              ||lower(object_name)
              ||' compile body;' , 'alter '
              ||lower(object_type)
              ||' '
              ||lower(owner)
              ||'.'
              ||lower(object_name)
              ||' compile;') cmd
from   dba_objects
where  status='INVALID'
/
spool off
---------------------
Session memory usage-
---------------------
1.  To understand  where memory  is wasted,  please check  the status  column in
v$session  view.  Are there  INACTIVE  views? If  yes,  to automate  cleanup  of
INACTIVE sessions you can create a profile with an appropriate IDLE_TIME setting
and  assign  that  profile  to  the  users.  -  Note:159978.1:  How  To Automate
Disconnection of Idle Sessions, outlines the steps to setup IDLE_TIME for this.
2. If  there no  inactive sessions,  please contact  the application provider to
find if connection pooling is used  and to check why connections are  not closed
gracefully.
3.  Regarding the  memory consumption  - pllease  check if  there is  a certain
session for which the memory consumption increases consistently. This is because
you mentioned  that from  12 sessions  consuming 515M,  it has  increased to  42
session with 1.5G which is basically a proportional increase.
You can use:
SQL> col name format a30
SQL> select sid,name,value
     from
     v$statname n,v$sesstat s
     where n.STATISTIC# = s.STATISTIC#
     and name like 'session%memory%'
     order by 3 asc;
Please refer to :
- Note.233869.1 Ext/Pub Diagnosing and Resolving ORA-4030 errors Some operations
will  require  lots  of process  memory  like  huge PL/SQL  tables  or  big sort
operations. In these cases, the processes will run for a certain period of  time
before getting the ora-4030 error, hopefully  allowing us to find out where  and
why  the memory  is allocated.  You can  use the  following query  to find  out
oracle's idea of PGA and UGA size for the oracle processes.
- Note.822527.1 Int/Pub How To Find Where The Memory Is Growing For A Process
----------------------------
-- Checking after migration:
----------------------------
cat > chkdbversion.sql
set linesize 100
select name "Database" from v$database;
select banner "Database version" from v$version;
prompt Listing registry components:
select comp_id, version, status from dba_registry;
prompt Listing database connection status using TNSPING:
prompt
host tnsping $ORACLE_SID

cat > chkdbversion.sh
#!/usr/bin/ksh
for i in `ps -ef|grep pmon | grep ora | grep -v grep | awk '{print $NF}' | cut -c10-40`
do
        USER=`ps -ef|grep $i | grep pmon | awk '{print $1}'`
        DB=$i
        echo $DB   $USER
        su - $USER -c "export ORACLE_SID=$DB;sqlplus '/ as sysdba' @//chkdbversion.sql"  < /dev/null
done
echo ' '
echo ' '
ps -ef|egrep -i "inherit|pmon"
echo ' '