Search This Blog

Total Pageviews

Saturday, 31 December 2022

Oracle How to Restore Of Single PDB via RMAN

		 
Oracle How to Restore Of Single PDB via RMAN 
Rman to Restore Of Single PDB in Multitenant	



Aim to restore only ORCL database ONLY via rman !!!!
		
SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 ORCL                           READ WRITE NO   <<<< only this database !!!
         4 ORCLD                          READ WRITE NO

 
		 
=========		 

		 
RMAN> restore controlfile from '/home/oracle/RmanBackup/ORCLCDB_T20221230_cf15_p1_t1124819364';

Starting restore at 31-12-2022 02:43:09
using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=424 device type=DISK

channel ORA_DISK_1: restoring control file
channel ORA_DISK_1: restore complete, elapsed time: 00:00:01
output file name=/u01/app/oracle/oradata/ORCLCDB/control01.ctl
Finished restore at 31-12-2022 02:43:12

RMAN> alter database mount ;


released channel: ORA_DISK_1
Statement processed



from another session !!!


set linesize 300 pagesize 100
col inst_id                      for 9999999                 heading 'Instance #'
col file_nr                      for 9999999                 heading 'File #'
col file_name                    for A70                     heading 'File name'
col checkpoint_change_nr         for 99999999999999          heading 'Checkpoint #'
col checkpoint_change_time       for A20                     heading 'Checkpoint time'
col last_change_nr               for 99999999999999          heading 'Last change #'
col SCNStatus for a15
SELECT
 fe.inst_id,
fe.CON_ID,  ---- for >12c
 fe.fenum file_nr,
 fn.fnnam file_name,
 TO_NUMBER (fe.fecps) checkpoint_change_nr,
 fe.fecpt checkpoint_change_time,
fe.fests last_change_nr,
NVL2(fe.fecps, '<-Good', 'Recover to this scn') SCNStatus,  ---- Recover to max 'scn'
 DECODE (
 fe.fetsn,
 0, DECODE (BITAND (fe.festa, 2), 0, 'SYSOFF', 'SYSTEM'),
 DECODE (BITAND (fe.festa, 18),
         0, 'OFFLINE',
         2, 'ONLINE',
            'RECOVER')
 ) status
FROM x$kccfe fe, x$kccfn fn
WHERE ( (fe.fepax != 65535 AND fe.fepax != 0 )  OR (fe.fepax = 65535 OR fe.fepax = 0) )
 AND fn.fnfno = fe.fenum
 AND fe.fefnh = fn.fnnum
 AND fe.fedup != 0
 AND fn.fntyp = 4
 AND fn.fnnam IS NOT NULL
 AND BITAND (fn.fnflg, 4) != 4
ORDER BY fe.fenum
;
 
		 
		 Instance #     CON_ID   File # File name                                                                 Checkpoint # Checkpoint time      Last change # SCNSTATUS       STATUS
---------- ---------- -------- ---------------------------------------------------------------------- --------------- -------------------- -------------------- --------------- -------
         1          1        1 /u01/app/oracle/oradata/ORCLCDB/system01.dbf                                   4079968 12/30/2022 17:49:19<-Good          SYSTEM
         1          1        3 /u01/app/oracle/oradata/ORCLCDB/sysaux01.dbf                                   4079968 12/30/2022 17:49:19<-Good          ONLINE
         1          2        5 /u01/app/oracle/oradata/ORCLCDB/pdbseed/system01.dbf                           2163739 05/31/2019 15:32:31<-Good          SYSOFF
         1          2        6 /u01/app/oracle/oradata/ORCLCDB/pdbseed/sysaux01.dbf                           2163739 05/31/2019 15:32:31<-Good          OFFLINE
         1          1        7 /u01/app/oracle/oradata/ORCLCDB/users01.dbf                                    4079968 12/30/2022 17:49:19<-Good          ONLINE
         1          2        8 /u01/app/oracle/oradata/ORCLCDB/pdbseed/undotbs01.dbf                          2163739 05/31/2019 15:32:31<-Good          OFFLINE
         1          3        9 /u01/app/oracle/oradata/ORCLCDB/orcl/system01.dbf                              4079968 12/30/2022 17:49:19<-Good          SYSTEM
         1          3       10 /u01/app/oracle/oradata/ORCLCDB/orcl/sysaux01.dbf                              4079968 12/30/2022 17:49:19<-Good          ONLINE
         1          3       12 /u01/app/oracle/oradata/ORCLCDB/orcl/users01.dbf                               4079968 12/30/2022 17:49:19<-Good          ONLINE
         1          3       13 /u01/app/oracle/oradata/ORCLCDB/orcl/APEX_1291597703607401.dbf                 4079968 12/30/2022 17:49:19<-Good          ONLINE
         1          1       14 /u01/app/oracle/oradata/ORCLCDB/undotbs2.dbf                                   4079968 12/30/2022 17:49:19<-Good          ONLINE
         1          3       15 /u01/app/oracle/oradata/ORCLCDB/orcl/undotbs2.dbf                              4079968 12/30/2022 17:49:19<-Good          ONLINE
         1          4       16 /u01/app/oracle/oradata/ORCLCDB/orcld/system01.dbf                             4078427 12/30/2022 17:42:42<-Good          SYSOFF
         1          4       17 /u01/app/oracle/oradata/ORCLCDB/orcld/sysaux01.dbf                             4078427 12/30/2022 17:42:42<-Good          OFFLINE
         1          4       18 /u01/app/oracle/oradata/ORCLCDB/orcld/undotbs01.dbf                            4078427 12/30/2022 17:42:42<-Good          OFFLINE
         1          4       19 /u01/app/oracle/oradata/ORCLCDB/orcld/orcld.dbf                                4078427 12/30/2022 17:42:42<-Good          OFFLINE

16 rows selected.


Find out the scn from above SQL



run { set until scn 4079968;
            restore database root ;
            restore database "PDB$SEED";
            restore database ORCL;
                        }


Starting restore at 31-12-2022 02:50:50
Starting implicit crosscheck backup at 31-12-2022 02:50:50
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=414 device type=DISK
Crosschecked 14 objects
Finished implicit crosscheck backup at 31-12-2022 02:50:51

Starting implicit crosscheck copy at 31-12-2022 02:50:51
using channel ORA_DISK_1
Crosschecked 4 objects
Finished implicit crosscheck copy at 31-12-2022 02:50:51

searching for all files in the recovery area
cataloging files...
no files cataloged

using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00001 to /u01/app/oracle/oradata/ORCLCDB/system01.dbf
channel ORA_DISK_1: restoring datafile 00007 to /u01/app/oracle/oradata/ORCLCDB/users01.dbf
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_db_s3_p1_t1124819247
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_db_s3_p1_t1124819247 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:25
channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00003 to /u01/app/oracle/oradata/ORCLCDB/sysaux01.dbf
channel ORA_DISK_1: restoring datafile 00014 to /u01/app/oracle/oradata/ORCLCDB/undotbs2.dbf
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_db_s5_p1_t1124819293
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_db_s5_p1_t1124819293 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:15
Finished restore at 31-12-2022 02:51:33

Starting restore at 31-12-2022 02:51:33
using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00005 to /u01/app/oracle/oradata/ORCLCDB/pdbseed/system01.dbf
channel ORA_DISK_1: restoring datafile 00008 to /u01/app/oracle/oradata/ORCLCDB/pdbseed/undotbs01.dbf
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_db_s7_p1_t1124819319
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_db_s7_p1_t1124819319 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:15
channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00006 to /u01/app/oracle/oradata/ORCLCDB/pdbseed/sysaux01.dbf
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_db_s9_p1_t1124819336
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_db_s9_p1_t1124819336 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:15
Finished restore at 31-12-2022 02:52:03

Starting restore at 31-12-2022 02:52:03
using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00010 to /u01/app/oracle/oradata/ORCLCDB/orcl/sysaux01.dbf
channel ORA_DISK_1: restoring datafile 00013 to /u01/app/oracle/oradata/ORCLCDB/orcl/APEX_1291597703607401.dbf
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_db_s2_p1_t1124819247
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_db_s2_p1_t1124819247 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:35
channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00009 to /u01/app/oracle/oradata/ORCLCDB/orcl/system01.dbf
channel ORA_DISK_1: restoring datafile 00012 to /u01/app/oracle/oradata/ORCLCDB/orcl/users01.dbf
channel ORA_DISK_1: restoring datafile 00015 to /u01/app/oracle/oradata/ORCLCDB/orcl/undotbs2.dbf
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_db_s4_p1_t1124819293
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_db_s4_p1_t1124819293 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:25
Finished restore at 31-12-2022 02:53:04






RMAN> recover database ;

Starting recover at 31-12-2022 03:27:16
using channel ORA_DISK_1
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of recover command at 12/31/2022 03:27:16
RMAN-07551: data file 16 must be restored or preplugin recovery must be completed


******************************************************************************************************************
How to use Rman to Restore Of Single PDB in Multitenant to Alternate Server (Doc ID 2142675.1)
Skip the PDB's database not required during the recovery stage by using 'Skip forever tablespace >'

*******************************************************************************************************************




RMAN> report schema ;

RMAN-06139: warning: control file is not current for REPORT SCHEMA
Report of database schema for database with db_unique_name ORCLCDB

List of Permanent Datafiles
===========================
File Size(MB) Tablespace           RB segs Datafile Name
---- -------- -------------------- ------- ------------------------
1    910      SYSTEM               ***     /u01/app/oracle/oradata/ORCLCDB/system01.dbf
3    570      SYSAUX               ***     /u01/app/oracle/oradata/ORCLCDB/sysaux01.dbf
5    270      PDB$SEED:SYSTEM      ***     /u01/app/oracle/oradata/ORCLCDB/pdbseed/system01.dbf
6    330      PDB$SEED:SYSAUX      ***     /u01/app/oracle/oradata/ORCLCDB/pdbseed/sysaux01.dbf
7    5        USERS                ***     /u01/app/oracle/oradata/ORCLCDB/users01.dbf
8    100      PDB$SEED:UNDOTBS1    ***     /u01/app/oracle/oradata/ORCLCDB/pdbseed/undotbs01.dbf
9    410      ORCL:SYSTEM          ***     /u01/app/oracle/oradata/ORCLCDB/orcl/system01.dbf
10   1200     ORCL:SYSAUX          ***     /u01/app/oracle/oradata/ORCLCDB/orcl/sysaux01.dbf
12   401      ORCL:USERS           ***     /u01/app/oracle/oradata/ORCLCDB/orcl/users01.dbf
13   2        ORCL:APEX_1291597703607401 ***     /u01/app/oracle/oradata/ORCLCDB/orcl/APEX_1291597703607401.dbf
14   50       UNDOTBS2             ***     /u01/app/oracle/oradata/ORCLCDB/undotbs2.dbf
15   50       ORCL:UNDOTBS2        ***     /u01/app/oracle/oradata/ORCLCDB/orcl/undotbs2.dbf
16   0        ORCLD:SYSTEM         ***     /u01/app/oracle/oradata/ORCLCDB/orcld/system01.dbf
17   0        ORCLD:SYSAUX         ***     /u01/app/oracle/oradata/ORCLCDB/orcld/sysaux01.dbf
18   0        ORCLD:UNDOTBS1       ***     /u01/app/oracle/oradata/ORCLCDB/orcld/undotbs01.dbf
19   0        ORCLD:ORCL1_USERS    ***     /u01/app/oracle/oradata/ORCLCDB/orcld/orcld.dbf

List of Temporary Files
=======================
File Size(MB) Tablespace           Maxsize(MB) Tempfile Name
---- -------- -------------------- ----------- --------------------
1    20       TEMP                 32767       /u01/app/oracle/oradata/ORCLCDB/temp01.dbf
2    36       PDB$SEED:TEMP        32767       /u01/app/oracle/oradata/ORCLCDB/pdbseed/temp012019-05-31_15-03-14-330-PM.dbf
3    36       ORCL:TEMP            32767       /u01/app/oracle/oradata/ORCLCDB/orcl/temp01.dbf
4    36       ORCLD:TEMP           32767       /u01/app/oracle/oradata/ORCLCDB/orcld/cl_ixantemp012019-05-31_15-03-14-330-PM.dbf




Now skip ORCLD pluggable and datafiles!!!


RMAN> recover database skip forever tablespace ORCLD:SYSTEM,ORCLD:ORCL1_USERS,ORCLD:SYSAUX,ORCLD:UNDOTBS1 ;


Starting recover at 31-12-2022 03:39:38
using channel ORA_DISK_1

Executing: alter database datafile 16 offline drop
Executing: alter database datafile 19 offline drop
Executing: alter database datafile 17 offline drop
Executing: alter database datafile 18 offline drop
starting media recovery

channel ORA_DISK_1: starting archived log restore to default destination
channel ORA_DISK_1: restoring archived log
archived log thread=1 sequence=33
channel ORA_DISK_1: restoring archived log
archived log thread=1 sequence=34
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_arch_s13_p1_t1124819360
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_arch_s13_p1_t1124819360 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:01
archived log file name=/u01/app/oracle/fast_recovery_area/ORCLCDB/archivelog/2022_12_31/o1_mf_1_33_ktzxbcob_.arc thread=1 sequence=33
channel default: deleting archived log(s)
archived log file name=/u01/app/oracle/fast_recovery_area/ORCLCDB/archivelog/2022_12_31/o1_mf_1_33_ktzxbcob_.arc RECID=6 STAMP=1124854779
archived log file name=/u01/app/oracle/fast_recovery_area/ORCLCDB/archivelog/2022_12_31/o1_mf_1_34_ktzxbcoy_.arc thread=1 sequence=34
channel default: deleting archived log(s)
archived log file name=/u01/app/oracle/fast_recovery_area/ORCLCDB/archivelog/2022_12_31/o1_mf_1_34_ktzxbcoy_.arc RECID=5 STAMP=1124854779
channel ORA_DISK_1: starting archived log restore to default destination
channel ORA_DISK_1: restoring archived log
archived log thread=1 sequence=35
channel ORA_DISK_1: reading from backup piece /home/oracle/RmanBackup/ORCLCDB_T20221230_arch_s14_p1_t1124819361
channel ORA_DISK_1: piece handle=/home/oracle/RmanBackup/ORCLCDB_T20221230_arch_s14_p1_t1124819361 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:01
archived log file name=/u01/app/oracle/fast_recovery_area/ORCLCDB/archivelog/2022_12_31/o1_mf_1_35_ktzxbf4z_.arc thread=1 sequence=35
channel default: deleting archived log(s)
archived log file name=/u01/app/oracle/fast_recovery_area/ORCLCDB/archivelog/2022_12_31/o1_mf_1_35_ktzxbf4z_.arc RECID=7 STAMP=1124854781
unable to find archived log
archived log thread=1 sequence=36
RMAN-00571: ===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
RMAN-00571: ===========================================================
RMAN-03002: failure of recover command at 12/31/2022 03:39:42
RMAN-06054: media recovery requesting unknown archived log for thread 1 with sequence 36 and starting SCN of 4079968

RMAN>

RMAN> alter database open resetlogs;
Statement processed

Recovey completed ....




SQL> select open_mode,current_scn,checkpoint_change#,archive_change#,controlfile_change# from v$database;

OPEN_MODE            CURRENT_SCN CHECKPOINT_CHANGE# ARCHIVE_CHANGE# CONTROLFILE_CHANGE#
-------------------- ----------- ------------------ --------------- -------------------
READ WRITE               4092115            4079972               0             4092072




set linesize 300
col NAME for a70
col ERROR for a15
 select * from (select file#,con_id,tablespace_name,status,error ,recover ,fuzzy ,checkpoint_time checkpoint from v$datafile_header)
natural join (select hxfil file#, fhsta, fhscn, fhrba_seq, fhafs from x$kcvfhall);





    FILE#     CON_ID TABLESPACE_NAME                STATUS  ERROR           REC FUZ CHECKPOIN      FHSTA FHSCN                 FHRBA_SEQ FHAFS
---------- ---------- ------------------------------ ------- --------------- --- --- --------- ---------- -------------------- ---------- --------------------
         1          1 SYSTEM                         ONLINE                  NO  YES 31-DEC-22       8196 4079972                       1 0
         3          1 SYSAUX                         ONLINE                  NO  YES 31-DEC-22          4 4079972                       1 0
         5          2 SYSTEM                         ONLINE                      NO  31-MAY-19       8192 2163739                       7 0
         6          2 SYSAUX                         ONLINE                      NO  31-MAY-19          0 2163739                       7 0
         7          1 USERS                          ONLINE                  NO  YES 31-DEC-22          4 4079972                       1 0
         8          2 UNDOTBS1                       ONLINE                      NO  31-MAY-19          0 2163739                       7 0
         9          3 SYSTEM                         ONLINE                  NO  YES 31-DEC-22       8196 4080979                       1 0
        10          3 SYSAUX                         ONLINE                  NO  YES 31-DEC-22          4 4080979                       1 0
        12          3 USERS                          ONLINE                  NO  YES 31-DEC-22          4 4080979                       1 0
        13          3 APEX_1291597703607401          ONLINE                  NO  YES 31-DEC-22          4 4080979                       1 0
        14          1 UNDOTBS2                       ONLINE                  NO  YES 31-DEC-22          4 4079972                       1 0
        15          3 UNDOTBS2                       ONLINE                  NO  YES 31-DEC-22          4 4080979                       1 0
        16          4                                OFFLINE FILE NOT FOUND                             0 0                             0 0
        17          4                                OFFLINE FILE NOT FOUND                             0 0                             0 0
        18          4                                OFFLINE FILE NOT FOUND                             0 0                             0 0
        19          4                                OFFLINE FILE NOT FOUND                             0 0                             0 0

16 rows selected.

SQL>



SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 ORCL                           READ WRITE NO
         4 ORCLD                          MOUNTED  <<<<<
SQL>


      

Friday, 30 December 2022

Oracle Recover from a loss of the SYSTEM tablespace datafile


recover system datafile  lost

Recover from a loss of the SYSTEM tablespace datafile 



Error on alert log
ORA-01110: data file 1: '/u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1'
ORA-01565: error in identifying file '/u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1'   ------<<<<<<<
ORA-27037: unable to obtain file status
Linux-x86_64 Error: 2: No such file or directory
 


We should have valid backup to recover system datafile  ...


export NLS_DATE_FORMAT='dd-mm-yyyy hh:mi:ss'
rman target / | tee rman.log
run {
  allocate channel ch1 device type DISK;
  allocate channel ch2 device type DISK;
  backup incremental level=0 tag "RMANFULL" format '/u01/app/oracle/RmanBackup/%d_T%T_db_s%s_p%p_t%t' database filesperset 4 plus archivelog tag "RMANFULL";
 sql "alter system archive log current";
  backup format '/u01/app/oracle/RmanBackup/%d_T%T_arch_s%s_p%p_t%t' archivelog all filesperset 4 tag "RMANFULL";
  backup format '/u01/app/oracle/RmanBackup/%d_T%T_cf%s_p%p_t%t' current controlfile tag "RMANFULL";
sql "alter system archive log current";
restore database preview;
}



Simulate the failure - by moving the system datafile:


[oracle@wcp12cr2 Datafile]$ mv data_D-ORCL_TS-SYSTEM_FNO-1 data_D-ORCL_TS-SYSTEM_FNO-1-ORIG



SQL> shutdown immediate ;
ORA-01116: error in opening database file 1
ORA-01110: data file 1: '/u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1'
ORA-27041: unable to open file
Linux-x86_64 Error: 2: No such file or directory
Additional information: 3
SQL>






from alert log 

2022-12-29T13:34:41.592711-08:00
Errors in file /u01/app/oracle/diag/rdbms/orcl/orcl/trace/orcl_m000_10344.trc:
ORA-01110: data file 1: '/u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1'
ORA-01565: error in identifying file '/u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1'   ------<<<<<<<
ORA-27037: unable to obtain file status
Linux-x86_64 Error: 2: No such file or directory
Additional information: 7
Checker run found 1 new persistent data failures
2022-12-29T13:35:25.549197-08:00
OS process OFSD (ospid 3088) idle for 30 seconds, exiting



--Check the status of datafiles 

set pagesize 300 linesize 200
col NAME for a70
col recover for a12
col , error for a20
select file#,NAME,checkpoint_change#, status, recover, error from v$datafile_header;


SQL> SQL> SQL>
     FILE# NAME                                                                   CHECKPOINT_CHANGE# STATUS  REC
---------- ---------------------------------------------------------------------- ------------------ ------- ---
         1                                                                                         0 ONLINE        <<<<< lost file 
         2 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_OPSS_FNO-2                      3361521 ONLINE  NO
         3 /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSAUX_FNO-3                              3361521 ONLINE  NO
         4 /u01/app/oracle/Datafile/data_D-ORCL_TS-UNDOTBS1_FNO-4                            3361521 ONLINE  NO
         5 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_PORTLET_FNO-5                   3361521 ONLINE  NO
         6 /u01/app/oracle/Datafile/data_D-ORCL_TS-USERS_FNO-6                               3361521 ONLINE  NO
         7 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_WEBCENTER_FNO-7                 3361521 ONLINE  NO
         8 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_DISCUSS_FNO-8                   3361521 ONLINE  NO
         9 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_STB_FNO-9                           3361521 ONLINE  NO
        10 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAU_FNO-10                          3361521 ONLINE  NO
        11 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_MDS_FNO-11                          3361521 ONLINE  NO
        12 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_OCS_FNO-12                          3361521 ONLINE  NO
        13 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_ACTIVITY_FNO-13                 3361521 ONLINE  NO
        14 /u01/app/oracle/Datafile/data_D-ORCL_TS-DBFS_TS_FNO-14                            3361521 ONLINE  NO

14 rows selected.



Restore and Recover the system datafile using backups


RMAN> restore datafile 1;

Starting restore at 29-12-2022 01:42:42
using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore
channel ORA_DISK_1: specifying datafile(s) to restore from backup set
channel ORA_DISK_1: restoring datafile 00001 to /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1
channel ORA_DISK_1: reading from backup piece /u01/app/oracle/RmanBackup/ORCL_T20221229_db_s19_p1_t1124716704
channel ORA_DISK_1: piece handle=/u01/app/oracle/RmanBackup/ORCL_T20221229_db_s19_p1_t1124716704 tag=RMANFULL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:25
Finished restore at 29-12-2022 01:43:08


SQL> SQL> /

     FILE# NAME                                                                   CHECKPOINT_CHANGE# STATUS  REC
---------- ---------------------------------------------------------------------- ------------------ ------- ---
         1 /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1                                    0 ONLINE
         2 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_OPSS_FNO-2                      3361521 ONLINE  NO
         3 /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSAUX_FNO-3                              3361521 ONLINE  NO
         4 /u01/app/oracle/Datafile/data_D-ORCL_TS-UNDOTBS1_FNO-4                            3361521 ONLINE  NO
         5 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_PORTLET_FNO-5                   3361521 ONLINE  NO
         6 /u01/app/oracle/Datafile/data_D-ORCL_TS-USERS_FNO-6                               3361521 ONLINE  NO
         7 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_WEBCENTER_FNO-7                 3361521 ONLINE  NO
         8 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_DISCUSS_FNO-8                   3361521 ONLINE  NO
         9 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_STB_FNO-9                           3361521 ONLINE  NO
        10 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAU_FNO-10                          3361521 ONLINE  NO
        11 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_MDS_FNO-11                          3361521 ONLINE  NO
        12 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_OCS_FNO-12                          3361521 ONLINE  NO
        13 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_ACTIVITY_FNO-13                 3361521 ONLINE  NO
        14 /u01/app/oracle/Datafile/data_D-ORCL_TS-DBFS_TS_FNO-14                            3361521 ONLINE  NO

14 rows selected.




RMAN> recover datafile 1;

Starting recover at 29-12-2022 01:44:29
using channel ORA_DISK_1

starting media recovery

archived log for thread 1 with sequence 3 is already on disk as file /u01/app/oracle/Archive/ORCL/archivelog/2022_12_29/o1_mf_1_3_ktw1221o_.arc
archived log for thread 1 with sequence 4 is already on disk as file /u01/app/oracle/Archive/ORCL/archivelog/2022_12_29/o1_mf_1_4_ktw124o0_.arc
archived log for thread 1 with sequence 5 is already on disk as file /u01/app/oracle/Archive/ORCL/archivelog/2022_12_29/o1_mf_1_5_ktw124sc_.arc
archived log for thread 1 with sequence 6 is already on disk as file /u01/app/oracle/Archive/ORCL/archivelog/2022_12_29/o1_mf_1_6_ktw12fc8_.arc
archived log file name=/u01/app/oracle/Archive/ORCL/archivelog/2022_12_29/o1_mf_1_3_ktw1221o_.arc thread=1 sequence=3
archived log file name=/u01/app/oracle/Archive/ORCL/archivelog/2022_12_29/o1_mf_1_4_ktw124o0_.arc thread=1 sequence=4
media recovery complete, elapsed time: 00:00:01
Finished recover at 29-12-2022 01:44:31

RMAN>



   FILE# NAME                                                                   CHECKPOINT_CHANGE# STATUS  REC
---------- ---------------------------------------------------------------------- ------------------ ------- ---
         1 /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1                              3382895 ONLINE  NO  <<<<<<<----- 10="" 11="" 12="" 13="" 14="" 2="" 3361521="" 3="" 4="" 5="" 6="" 7="" 8="" 9="" app="" atafile="" data_d-orcl_ts-dbfs_ts_fno-14="" data_d-orcl_ts-sysaux_fno-3="" data_d-orcl_ts-undotbs1_fno-4="" data_d-orcl_ts-users_fno-6="" data_d-orcl_ts-wcpvm_ias_activity_fno-13="" data_d-orcl_ts-wcpvm_ias_discuss_fno-8="" data_d-orcl_ts-wcpvm_ias_opss_fno-2="" data_d-orcl_ts-wcpvm_ias_portlet_fno-5="" data_d-orcl_ts-wcpvm_ias_webcenter_fno-7="" data_d-orcl_ts-wcpvm_iau_fno-10="" data_d-orcl_ts-wcpvm_mds_fno-11="" data_d-orcl_ts-wcpvm_ocs_fno-12="" data_d-orcl_ts-wcpvm_stb_fno-9="" no="" online="" oracle="" rman="" rows="" selected.="" u01=""> alter database open ;

Statement processed

RMAN>


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

now all the scn no are same 


SQL> r
  1* select file#,NAME,checkpoint_change#, status, recover from v$datafile_header

    FILE# NAME                                                                   CHECKPOINT_CHANGE# STATUS  RECOVER
---------- ---------------------------------------------------------------------- ------------------ ------- ------------
         1 /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1                              3402898 ONLINE  NO
         2 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_OPSS_FNO-2                      3402898 ONLINE  NO
         3 /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSAUX_FNO-3                              3402898 ONLINE  NO
         4 /u01/app/oracle/Datafile/data_D-ORCL_TS-UNDOTBS1_FNO-4                            3402898 ONLINE  NO
         5 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_PORTLET_FNO-5                   3402898 ONLINE  NO
         6 /u01/app/oracle/Datafile/data_D-ORCL_TS-USERS_FNO-6                               3402898 ONLINE  NO
         7 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_WEBCENTER_FNO-7                 3402898 ONLINE  NO
         8 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_DISCUSS_FNO-8                   3402898 ONLINE  NO
         9 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_STB_FNO-9                           3402898 ONLINE  NO
        10 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAU_FNO-10                          3402898 ONLINE  NO
        11 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_MDS_FNO-11                          3402898 ONLINE  NO
        12 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_OCS_FNO-12                          3402898 ONLINE  NO
        13 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_ACTIVITY_FNO-13                 3402898 ONLINE  NO
        14 /u01/app/oracle/Datafile/data_D-ORCL_TS-DBFS_TS_FNO-14                            3402898 ONLINE  NO

14 rows selected.



 set pages 200 lines 200
col FILE_NAME for a70
 select FILE_ID,TABLESPACE_NAME,FILE_NAME,STATUS from dba_data_files;

   FILE_ID TABLESPACE_NAME                FILE_NAME                                                              STATUS
---------- ------------------------------ ---------------------------------------------------------------------- ---------
         1 SYSTEM                         /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1                   AVAILABLE
         3 SYSAUX                         /u01/app/oracle/Datafile/data_D-ORCL_TS-SYSAUX_FNO-3                   AVAILABLE
         4 UNDOTBS1                       /u01/app/oracle/Datafile/data_D-ORCL_TS-UNDOTBS1_FNO-4                 AVAILABLE
         6 USERS                          /u01/app/oracle/Datafile/data_D-ORCL_TS-USERS_FNO-6                    AVAILABLE
         2 WCPVM_IAS_OPSS                 /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_OPSS_FNO-2           AVAILABLE
         5 WCPVM_IAS_PORTLET              /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_PORTLET_FNO-5        AVAILABLE
         7 WCPVM_IAS_WEBCENTER            /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_WEBCENTER_FNO-7      AVAILABLE
         8 WCPVM_IAS_DISCUSS              /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_DISCUSS_FNO-8        AVAILABLE
         9 WCPVM_STB                      /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_STB_FNO-9                AVAILABLE
        10 WCPVM_IAU                      /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAU_FNO-10               AVAILABLE
        11 WCPVM_MDS                      /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_MDS_FNO-11               AVAILABLE
        12 WCPVM_OCS                      /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_OCS_FNO-12               AVAILABLE
        13 WCPVM_IAS_ACTIVITY             /u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_ACTIVITY_FNO-13      AVAILABLE
        14 DBFS_TS                        /u01/app/oracle/Datafile/data_D-ORCL_TS-DBFS_TS_FNO-14                 AVAILABLE

14 rows selected.

=====


SET LINES 200 pagesize 300
COL name             FORM a80
COL status           FORM A12
COL file#            FORM 9999
COL control_file_SCN FORM 999999999999999
COL datafile_SCN     FORM 999999999999999
--
SELECT
 a.name
,a.status
,a.file#
,a.checkpoint_change# control_file_SCN
,b.checkpoint_change# datafile_SCN
,CASE
   WHEN ((a.checkpoint_change# - b.checkpoint_change#) = 0) THEN 'Startup Normal'
   WHEN ((b.checkpoint_change#) = 0)                        THEN 'File Missing?'
   WHEN ((a.checkpoint_change# - b.checkpoint_change#) > 0) THEN 'Media Rec. Req.'
   WHEN ((a.checkpoint_change# - b.checkpoint_change#) < 0) THEN 'Old Control File'
   ELSE 'what the ?'
 END datafile_status
FROM v$datafile        a -- control file SCN for datafile
    ,v$datafile_header b -- datafile header SCN
WHERE a.file# = b.file#
ORDER BY a.file#;


NAME                                                                             STATUS       FILE# CONTROL_FILE_SCN     DATAFILE_SCN DATAFILE_STATUS
-------------------------------------------------------------------------------- ------------ ----- ---------------- ---------------- ----------------
/u01/app/oracle/Datafile/data_D-ORCL_TS-SYSTEM_FNO-1                             SYSTEM           1          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_OPSS_FNO-2                     ONLINE           2          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-SYSAUX_FNO-3                             ONLINE           3          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-UNDOTBS1_FNO-4                           ONLINE           4          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_PORTLET_FNO-5                  ONLINE           5          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-USERS_FNO-6                              ONLINE           6          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_WEBCENTER_FNO-7                ONLINE           7          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_DISCUSS_FNO-8                  ONLINE           8          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_STB_FNO-9                          ONLINE           9          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAU_FNO-10                         ONLINE          10          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_MDS_FNO-11                         ONLINE          11          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_OCS_FNO-12                         ONLINE          12          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-WCPVM_IAS_ACTIVITY_FNO-13                ONLINE          13          3405085          3405085 Startup Normal
/u01/app/oracle/Datafile/data_D-ORCL_TS-DBFS_TS_FNO-14                           ONLINE          14          3405085          3405085 Startup Normal

14 rows selected.



Tuesday, 20 December 2022

Oracle DBA unix useful command

Unix for the DBA How to kill all similar processes with single command (in this case opmn)
 

stty erase ^?
 stty erase ^H

ps -ef | grep opmn |grep -v grep | awk ‘{print $2}’ |xargs -i kill -9 {}
Locating Files under a particular directory

find . -print |grep -i test.sql

 Using AWK in UNIX

To remove a specific column of output from a UNIX command – for example to determine the UNIX process Ids for all Oracle processes on server (second column)

ps -ef |grep -i oracle |awk '{ print $2 }'

Changing the standard prompt for Oracle Users

Edit the .profile for the oracle user

PS1="`hostname`*$ORACLE_SID:$PWD>"

 Display top 10 CPU consumers using the ps command

/usr/ucb/ps auxgw | head -11

 Show number of active Oracle dedicated connection users for a particular ORACLE_SID

ps -ef | grep $ORACLE_SID|grep -v grep|grep -v ora_|wc -l

 Display the number of CPU’s in Solaris

psrinfo -v | grep "Status of processor"|wc -l

Display the number of CPU’s in AIX

lsdev -C | grep Process|wc -l

Display RAM Memory size on Solaris

prtconf |grep -i mem

Display RAM memory size on AIX

First determine name of memory device

lsdev -C |grep mem

then assuming the name of the memory device is ‘mem0’

lsattr -El mem0

Swap space allocation and usage

Solaris : swap -s or swap -l
Aix : lsps -a

 Total number of semaphores held by all instances on server

ipcs -as | awk '{sum += $9} END {print sum}'

View allocated RAM memory segments

ipcs -pmb

Manually deallocate shared memeory segments

ipcrm -m ''

 Show mount points for a disk in AIX

lspv -l hdisk13

 Display amount of occupied space (in KB) for a file or collection of files in a directory or sub-directory

du -ks * | sort -n| tail

Display total file space in a directory

du -ks .

 Cleanup any unwanted trace files more than seven days old

find . *.trc -mtime +7 -exec rm {} \;

 Locate Oracle files that contain certain strings

find . -print | xargs grep rollback

 Locate recently created UNIX files (in the past one day)

find . -mtime -1 -print

 Finding large files on the server (more than 100MB in size)

find . -size +102400 -print

Remove DOS CR/LFs (^M)
Remove DOS style CR/LF characters (^M) from UNIX files using:

    sed -e 's/^M$//' filename > tempfile


sar
$ sar -u 10 8
Reports CPU Utilization (10 seconds apart; 8 times):
Time 	%usr 	%sys 	%wio 	%idle
11:57:31 	72 	28 	0 	0
11:57:41 	70 	30 	0 	0
11:57:51 	70 	30 	0 	0
11:58:01 	68 	32 	0 	0
11:58:11 	67 	33 	0 	0
11:58:21 	65 	28 	0 	7
11:58:31 	73 	27 	0 	0
11:58:41 	69 	31 	0 	0
Average 	69 	30 	0 	1

%usr: Percent of CPU in user mode
%sys: Percent of CPU in system mode
%wio: Percent of CPU running idle with a process waiting for block I/O
%idle: Percent of CPU that is idle


mpstat
$ mpstat 10 2
Reports per-processor statistics on Sun Solaris (10 seconds apart; 8 times):
CPU 	minf 	mjf 	xcal 	intr 	ithr 	csw 	icsw 	migr 	smtx 	srw 	syscl 	usr 	sys 	wt 	idl
0 	6 	8 	0 	438 	237 	246 	85 	0 	0 	21 	8542 	23 	9 	9 	59
0 	0 	29 	0 	744 	544 	494 	206 	0 	0 	95 	110911 	65 	29 	6 	0
ps
$ ps -e -o pcpu -o pid -o user -o args | sort -k 1 | tail -21r
Displays the top 20 CPU users on the system.
%CPU 	PID 	USER 	COMMAND
78.1 	4789 	oracle 	ora_dbwr_DDDS2
8.5 	4793 	oracle 	ora_lgwr_DDDS2
2.4 	6206 	oracle 	oracleDDDS2 (LOCAL=NO)
0.1 	4797 	oracle 	ora_smon_DDDS2
0.1 	6207 	oracle 	oracleDDDS2 (LOCAL=NO)
etc. 	etc. 	etc. 	etc.

The PID column can then be matched with the SPID column on the V$PROCESS view to provide more information on the process:

    SELECT a.username, 
           a.osuser, 
           a.program, 
           spid, 
           sid, 
           a.serial#
    FROM   v$session a,
           v$process b
    WHERE  a.paddr = b.addr
    AND    spid = '&pid';


CRON
There are two methods of editing the crontab file. First you can use the "crontab -l > filename" option to list the contents and pipe this to a file. Once you've editied the file you can then apply it using the "crontab filename":

    * Login as root
    * crontab -l > newcron
    * Edit newcron file.
    * crontab newcron

Alternatively you can use the "crontab -e" option to edit the crontab file directly.

The entries have the following elements:

    field          allowed values
    -----          --------------
    minute         0-59
    hour           0-23
    day of month   1-31
    month          1-12
    day of week    0-7 (both 0 and 7 are Sunday)
    user           Valid OS user
    command        Valid command or script.

The first 5 fields can be specified using the following rules:

    *       - All available values or "first-last".
    3-4     - A single range representing each possible from the start to the end of the range inclusive.
    1,2,5,6 - A specific list of values.
    1-3,5-8 - A specific list of ranges.
    0-23/2  - Every other value in the specified range.

The following entry runs a cleanup script a 01:00 each Sunday. Any output or errors from the script are piped to /dev/null to prevent a buildup of mails to root:

    0 1 * * 0 /u01/app/oracle/dba/weekly_cleanup > /dev/null 2>&1


vmstat
$ vmstat 5 3
Displays system statistics (5 seconds apart; 3 times):
procs 	memory 	page 	disk 	faults 	cpu
r 	b 	w 	swap 	free 	re 	mf 	pi 	po 	fr 	de 	sr 	s0 	s1 	s2 	s3 	in 	sy 	cs 	us 	sy 	id
0 	0 	0 	28872 	8792 	8 	5 	172 	142 	210 	0 	24 	3 	11 	17 	2 	289 	1081 	201 	14 	6 	80
0 	0 	0 	102920 	1936 	1 	95 	193 	6 	302 	1264 	235 	12 	1 	0 	3 	240 	459 	211 	0 	2 	97
0 	0 	0 	102800 	1960 	0 	0 	0 	0 	0 	464 	0 	0 	0 	0 	0 	107 	146 	29 	0 	0 	100

Having any processes in the b or w columns is a sign of a problem system.
Having an id of 0 is a sign that the cpu is overburdoned.
Having high values in pi and po show excessive paging.

    * procs (Reports the number of processes in each of the following states)
          o r : in run queue
          o b : blocked for resources (I/O, paging etc.)
          o w : runnable but swapped
    * memory (Reports on usage of virtual and real memory)
          o swap : swap space currently available (Kbytes)
          o free : size of free list (Kbytes)
    * page (Reports information about page faults and paging activity (units per second)
          o re : page reclaims
          o mf : minor faults
          o pi : Kbytes paged in
          o po : Kbytes paged out
          o fr : Kbytes freed
          o de : anticipated short-term memory shortfall (Kbytes)
          o sr : pages scanned by clock algorith
    * disk (Reports the number of disk operations per second for up to 4 disks
    * faults (Reports the trap/interupt rates (per second)
          o in : (non clock) device interupts
          o si : system calls
          o cs : CPU context switches
    * cpu (Reports the breakdown of percentage usage of CPU time (averaged across all CPUs)
          o us : user time
          o si : system time
          o cs : idle time


File Exists Check
The Korn shell allows you to check for the presence of a file using the "test -s" command. In the following script a backup log is renamed and moved if it is present:

    #!/bin/ksh
    if test -s /backup/daily_backup.log
    then
      DATE_SUFFIX=`date +"%y""%m""%d""%H""%M"`
      mv /backup/daily_backup.log /backup/archive/daily_backup$DATE_SUFFIX.log
    fi

==


Automatic Startup Scripts on Linux
Create a file in the /etc/init.d/ directory, in this case the file is called myservice, containing the commands you wish to run at startup and/or shutdown.

Use the chmod command to set the privileges to 750:

    chmod 750 /etc/init.d/myservice

Link the file into the appropriate run-level script directories:

    ln -s /etc/init.d/myservice /etc/rc0.d/K10myservice
    ln -s /etc/init.d/myservice /etc/rc3.d/S99myservice

Associate the myservice service with the appropriate run levels:

    chkconfig --level 345 dbora on

The script should now be automatically run at startup and shutdown (with "start" or "stop" as a commandline parameter) like other service initialization scripts.

Wednesday, 14 December 2022

Oracle too many parse errors PARSE ERROR

Oracle too many parse errors PARSE ERROR


DB Alert log Filled With WARNING'S 'too many parse errors PARSE ERROR: ORA-00923' (Doc ID 2649163.1)

WARNING: too many parse errors, count



To find Sql id !!!




SQL ending up in the shared pool 

$ grep -c "SQL hash" alert_<DBName>.log
2027
$ grep -c "hash=0xbbcb647d" alert_<DBName>.log
2027 



test 


from https://jonathanlewis.wordpress.com/2017/10/06/12c-parse/

declare
        m1 number;
begin
        for i in 1..1000000 loop
        begin
                execute immediate 'select count(*) frm dual' into m1;
                dbms_output.put_line(m1);
        exception
                when others then null;
        end;
        end loop;
end;
/



from alert log !!!!

Additional information: hd=0x1002f46e0 phd=0x10cd45dc0 flg=0x28 cisid=0 sid=0 ciuid=0 uid=0
2022-12-14T04:42:30.206000-05:00
----- PL/SQL Call Stack -----
  object      line  object
  handle    number  name
0x1175e2778         6  anonymous block  <<<<<<<<-------------------Check This 
WARNING: too many parse errors, count=1010000 SQL hash=0x19a22496
PARSE ERROR: ospid=32580, error=923 for statement:
2022-12-14T04:42:30.219167-05:00
select count(*) frm dual
Additional information: hd=0x1002f46e0 phd=0x10cd45dc0 flg=0x28 cisid=0 sid=0 ciuid=0 uid=0
2022-12-14T04:42:30.219363-05:00
----- PL/SQL Call Stack -----
  object      line  object
  handle    number  name
  

0x1175e2778         6  anonymous block





set linesize 300 
col sql_text for a50 wrap
 select address,child_address, sql_text from V$sql where child_address like '%2778%';




set linesize 300
col sql_text for a50 wrap
select sql_id,address,child_address, sql_text from gv$sql where child_address like '%2778%';  --<<<< --- 0x1175e2778         6  anonymous block


SQL_ID        ADDRESS          CHILD_ADDRESS    SQL_TEXT
------------- ---------------- ---------------- --------------------------------------------------
2r9g466tw2h18 000000010CD45798 00000001175E2778 declare         m1 number; begin         for i in
                                                1..1000000 loop         begin                 exec
                                                ute immediate 'select count(*) frm dual' into m1;
                                                                dbms_output.put_line(m1);
                                                exception                 when others then null;
                                                       end;         end loop; end;



===

from 0x1175e2778         6  anonymous block 




set linesize 300
col sql_text for a50 wrap
select sql_id,address,child_address, sql_text from gv$sql where child_address like '%1175E2778%';


SQL_ID        ADDRESS          CHILD_ADDRESS    SQL_TEXT
------------- ---------------- ---------------- --------------------------------------------------
2r9g466tw2h18 000000010CD45798 00000001175E2778 declare         m1 number; begin         for i in
                                                1..1000000 loop         begin                 exec
                                                ute immediate 'select count(*) frm dual' into m1;
                                                                dbms_output.put_line(m1);
                                                exception                 when others then null;
                                                       end;         end loop; end;





set linesize 150 pagesize 300
col PLAN_TABLE_OUTPUT for a125

SELECT t.* FROM v$sql s, table(DBMS_XPLAN.DISPLAY_CURSOR(s.sql_id, s.child_number)) t 
WHERE 1=1
--and sql_text LIKE '%XXX%'
and sql_id = '&sql_id'
;





alter session set nls_date_format='dd-mon-yyyy hh24:mi:ss';
set pages 200  line 900
col sql_text for a80 
col PROGRAM for a20
con inst_id for 99
col MACHINE for a20
col CPU 9999999999
col kill for a17
col event for a40
select distinct * from (select ''''||s.sid ||','|| s.serial#||',@'||s.inst_id ||'''' kill,s.con_id,sa.sql_id,vp.spid,
sa.CPU_TIME "CPU",
round(s.last_call_et,0) ,
s.program 		"PROGRAM",
s.machine 		"MACHINE",
sw.event,s.logon_time,s.username,
s.status,s.osuser ,
sa.SQL_TEXT 		"SQL_TEXT"
from gv$sqlarea sa, gv$session s, gv$process vp, gv$session_wait sw
where sa.address = s.sql_address
and sw.sid = s.sid 
and s.serial# <> 1 
and s.status='ACTIVE'
and s.paddr = vp.addr 
and sw.event not like '%client%'
order by round(s.last_call_et,0) desc
)
;








Tuesday, 29 November 2022

SQL Monitoring

SQL Monitoring
Real-Time SQL Monitoring

set lines 1000 pages 9999
col sid 		for 9999
col serial 		for 999999
col status 		for a15
col username 		for a20
col sql_text 		for a30
col module 		for a30
col program 		for a30
col SQL_EXEC_START 	for a20
col kill 		for a17
SELECT * FROM
(SELECT ''''||sid ||','|| session_serial#||',@'||inst_id ||'''' kill,con_id,status
,username,sql_id,SQL_PLAN_HASH_VALUE,
sql_exec_id ,
MODULE,program,
TO_CHAR(sql_exec_start,'dd-mon-yyyy hh24:mi:ss') AS sql_exec_start,
ROUND(elapsed_time/1000000)                      AS "Elapsed (s)",
ROUND(cpu_time    /1000000)                      AS "CPU (s)",
substr(sql_text,1,30) sql_text
FROM gv$sql_monitor 
where 1=1 
and status='EXECUTING' 
and module not like '%emagent%'
ORDER BY sql_exec_start  desc
);




set lines 1000 pages 300

SELECT 
''''||sid ||','|| session_serial#||',@'||inst_id ||'''' kill,
sql_id,
sql_exec_id,
con_id,
ROUND(elapsed_time    /1000000)     	      AS "Elapsed (s)",
     ROUND(cpu_time             /1000000,3)   AS "CPU (s)",
     ROUND(queuing_time         /1000000,3)   AS "Queuing (s)",
     ROUND(application_wait_time/1000000,3)   AS "Appli wait (s)",
     ROUND(concurrency_wait_time/1000000,3)   AS "Concurrency wait (s)",
     ROUND(cluster_wait_time    /1000000,3)   AS "Cluster wait (s)",
     ROUND(user_io_wait_time    /1000000,3)   AS "User io wait (s)",
     ROUND(physical_read_bytes  /(1024*1024)) AS "Phys reads (MB)",
     ROUND(physical_write_bytes /(1024*1024)) AS "Phys writes (MB)",
     buffer_gets                              AS "Buffer gets",
     ROUND(plsql_exec_time/1000000,3)         AS "Plsql exec (s)",
     ROUND(java_exec_time /1000000,3)         AS "Java exec (s)",
    module,
    substr(sql_text,1,10) sql_text
     FROM gv$sql_monitor
     WHERE 1=1
    --and sql_id = '8cnh50qfgwg73'
    -- AND sql_exec_id = 16777270
     AND sql_exec_start > SYSTIMESTAMP - INTERVAL '60' second
and status='EXECUTING' 
and module not like '%emagent%'
;



set long 30000 pagesize 500 linesize 300
col frm         heading from 
select * from (select 'gv$sql' frm ,  sql_fulltext sql_text from gv$sql where sql_id='&&sql_id'
               union all
               select 'dba_hist', sql_text from dba_hist_sqltext where sql_id='&&sql_id' 
	);



select xmltype(binds_xml) from gv$sql_monitor where sid = &sid and status = 'EXECUTING';



alter session set "_rowsource_execution_statistics" = TRUE;
col PLAN_TABLE_OUTPUT for a200
SELECT * FROM TABLE(dbms_xplan.display_cursor(sql_id => '&sql_id', cursor_child_no => 0, FORMAT => 'ADVANCED +ROWS +BYTES +COST +PARALLEL +PARTITION +IOSTATS +MEMSTATS +ALIAS +PEEKED_BINDS +OUTLINE +PREDICATE -PROJECTION +REMOTE +NOTE'));




SET lines 300  pages 1000  LONG 999999  longchunksize 200
SELECT dbms_sqltune.report_sql_monitor_list(sql_id=>'&sql_id',report_level=>'ALL') AS report FROM dual;


SET lines 200 pages 1000 LONG 999999 longchunksize 200
SELECT dbms_sqltune.report_sql_monitor(sql_id=>'5137dabysdzpw',sql_exec_id=>16777218,sql_exec_start=> TO_DATE('29-nov-2022 05:59:27','dd-mon-yyyy hh24:mi:ss')
,report_level=>'ALL') AS report FROM dual;
 

-- sql html !!!

SET LONG 1000000  LONGCHUNKSIZE 1000000  LINESIZE 1000  PAGESIZE 0  TRIM ON  TRIMSPOOL ON ECHO OFF FEEDBACK OFF

SPOOL report_sql_detail.html

SELECT DBMS_SQLTUNE.report_sql_detail(
  sql_id       => '&sql_id',
  type         => 'ACTIVE',
  report_level => 'ALL'
  ) AS report
FROM dual;


======
                             
select sysdate,sysdate - 30/(24*60) "-30min" ,sysdate - 10/(24*60) "-10min" ,sysdate - 5/(24*60) "-5min" from dual;



SYSDATE          -30min           -10min           -5min
---------------- ---------------- ---------------- ----------------
30-11-2022 13:52 30-11-2022 13:22 30-11-2022 13:42 30-11-2022 13:47

set long 250000  longchunksize 65536  pagesize 100 trimspool on heading off
--set linesize 600
set  linesize 254
 column text_line format a254
select DBMS_SQLTUNE.REPORT_SQL_MONITOR_LIST(
         INST_ID => NULL
       , active_since_date => sysdate - 5/(24*60)
       , report_level => 'BASIC'
--       , SQL_ID => 'dqbzzupk4xuz5'
 ,type                    => 'TEXT'
       )
  from dual;

set heading on 


===

set linesize 255  pagesize 200  trimspool on long 200000
 
set heading off
 
 
column text_line format a254
define m_sql_id = '4mtury8zcpvkx'
 
spool rep_mon
 
SELECT  dbms_sqltune.report_sql_monitor(
                sql_id=> v.sql_id,
                sql_exec_id => v.max_sql_exec_id
				--  ,active_since_date => sysdate - 5/(24*60)
        ) text_line
from     (
        select
                sql_id,
                max(sql_exec_id)        max_sql_exec_id
        from     v$sql_monitor
        where 1=1
           and   sql_id = '&m_sql_id'
   and     status like 'DONE%'
    group by
                sql_id
        )       v
;
 

==========

#1: Issue an alter session set "_sqlmon_max_planlines" = 300;  <<<< SQL with a plan in excess of 300 lines should not be monitored

to change 

alter system  set "_sqlmon_max_planlines"=500 scope=memory sid='*';
or
alter session set "_sqlmon_max_planlines"=500;

#2: Use a /*+ monitor */ hint when running the query.




set linesize 300 pagesize 300
col KSPPINM for a35
col KSPPSTVL for a15
col KSPPDESC for a90
select ksppinm, ksppstvl, ksppdesc   from sys.x$ksppi a, sys.x$ksppsv b
 where a.indx=b.indx
  and lower(ksppinm) like lower('%sqlmon%')
order by ksppinm;

KSPPINM                             KSPPSTVL        KSPPDESC
----------------------------------- --------------- ------------------------------------------------------------------------------------------
_sqlmon_binds_xml_format            default         format of column binds_xml in [G]V$SQL_MONITOR
_sqlmon_max_plan                    1600            Maximum number of plans entry that can be monitored. Defaults to 20 per CPU
_sqlmon_max_planlines               300             Number of plan lines beyond which a plan cannot be monitored
_sqlmon_recycle_time                5               Minimum time (in s) to wait before a plan entry can be recycled
_sqlmon_threshold                   5               CPU/IO time threshold before a statement is monitored. 0 is disabled



Sunday, 20 November 2022

How to Deinstall Old Clusterware Home ?

How to Deinstall Old Clusterware Home Once Upgrade to Newer Version is Complete (Doc ID 1346305.1)

To remove old home, as clusterware user execute the following on any node:


## please replace $OLD_HOME with the path of pre-upgrade clusterware home
export ORACLE_HOME=$OLD_HOME

## detach OLD_HOME
$OLD_HOME/oui/bin/runInstaller -detachHome -silent ORACLE_HOME=$OLD_HOME

## confirm $OLD_HOME is removed from central inventory:
$NEW_HOME/OPatch/opatch lsinventory -all  

## remove files in OLD_HOME manually on all nodes:
/bin/rm -rf $OLD_HOME

unset ORACLE_HOME




If it fails for any reason, as clusterware user execute the following on all nodes:

export ORACLE_HOME=$OLD_HOME

## detach OLD_HOME
$OLD_HOME/oui/bin/runInstaller -detachHome -silent -local ORACLE_HOME=$OLD_HOME

## confirm $OLD_HOME is removed from central inventory:
$NEW_HOME/OPatch/opatch lsinventory -all  

## remove files in OLD_HOME manually on all nodes:
/bin/rm -rf $OLD_HOME

unset ORACLE_HOME

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

as grid 

[grid@rac02 ~]$ export ORACLE_HOME=/u01/app/18.0.0/gridexport ORACLE_HOME=/u01/app/18.0.0/grid
[grid@rac02 ~]$ export ORACLE_HOME=/u01/app/18.0.0/grid
[grid@rac02 ~]$ $ORACLE_HOME/oui/bin/runInstaller -detachHome -silent ORACLE_HOME=$ORACLE_HOME
Starting Oracle Universal Installer...

Checking swap space: must be greater than 500 MB.   Actual 15851 MB    Passed
The inventory pointer is located at /etc/oraInst.loc
'DetachHome' was successful.  <<<<<<

===
[grid@rac02 ~]$ export ORACLE_HOME=/u01/app/19.0.0/grid
[grid@rac02 ~]$ $ORACLE_HOME/OPatch/opatch lsinventory -all
Oracle Interim Patch Installer version 12.2.0.1.17
Copyright (c) 2022, Oracle Corporation.  All rights reserved.


Oracle Home       : /u01/app/19.0.0/grid
Central Inventory : /u01/app/oraInventory
   from           : /u01/app/19.0.0/grid/oraInst.loc
OPatch version    : 12.2.0.1.17
OUI version       : 12.2.0.7.0
Log file location : /u01/app/19.0.0/grid/cfgtoollogs/opatch/opatch2022-11-20_07-13-22AM_1.log

Lsinventory Output file location : /u01/app/19.0.0/grid/cfgtoollogs/opatch/lsinv/lsinventory2022-11-20_07-13-22AM.txt

--------------------------------------------------------------------------------
Local Machine Information::
Hostname: ibrac02.int.smq.datapipe.net
ARU platform id: 226
ARU platform description:: Linux x86-64

List of Oracle Homes:
  Name          Location
   OraDB12Home1         /u01/app/oracle/product/12.1.0/dbhome_1
   OraDB12Home2         /u01/app/oracle/product/12.2.0/dbhome_1
   OraDB12Home3         /u01/app/oracle/VIS/12.1.0
   OraDB18Home1         /u01/app/oracle/product/18.3.0
   OraGI19Home1         /u01/app/19.0.0/grid

Installed Top-level Products (1):

Oracle Grid Infrastructure 19c                                       19.0.0.0.0
There are 1 products installed in this Oracle Home.


Interim patches (4) :

Patch  29585399     : applied on Thu Apr 18 03:36:24 EDT 2019
Unique Patch ID:  22840393
Patch description:  "OCW RELEASE UPDATE 19.3.0.0.0 (29585399)"
   Created on 9 Apr 2019, 19:12:47 hrs PST8PDT
   Bugs fixed:
     27222128, 27572040, 27604329, 27760043, 27877830, 28302580, 28470673
     28621543, 28642469, 28699321, 28710663, 28755846, 28772816, 28785321
     28800508, 28808652, 28815557, 28847541, 28847572, 28870496, 28871040
     28874416, 28877252, 28881191, 28881848, 28888083, 28911140, 28925250
     28925460, 28935956, 28940472, 3, 28942694, 28951332, 28963036, 28968779
     28980448, 28995287, 29003207, 29003617, 29016294, 29018680, 29024876
     29026154, 29027933, 29047127, 29052850, 29058476, 29111631, 29112455

Friday, 18 November 2022

Oracle Logrotate


 Oracle Logrotate 

logrotate  grid -s /tmp/ostatus

If below error  

error: skipping  because parent directory has insecure permissions (It's world writable or writable by group which is not "root") Set "su" directive in config file to tell logrotate which user/group should be used for rotation.


Do following !!!

[root@rac02 logrotate.d]# ls -ltr /u01/app/grid/diag/tnslsnr/rac02/start/trace/start.log
-rwxrwxr-x 1 grid oinstall 670 Nov 20  2020 /u01/app/grid/diag/tnslsnr/rac02/start/trace/start.log

[root@rac02 logrotate.d]# vi grid
[root@rac02 logrotate.d]# logrotate  grid -s /tmp/ostatus



 pwd
/etc/logrotate.d



 cat grid
/u01/app/grid/diag/*/*/*/trace/*.log
    {
su grid oinstall   <<<<< user name and group name for files 
      daily
      rotate 7
      compress
      copytruncate
      missingok
      nodateext
      size 20M
   }


to test !!!!
logrotate  grid -s /tmp/ostatus






now no error 

 cat /tmp/ostatus
logrotate state -- version 2
"/u01/app/grid/diag/tnslsnr/rac02/listener_scan3/trace/listener_scan3.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/tnslsnr/rac02/listener_scan2/trace/listener_scan2.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/tnslsnr/rac02/mgmtlsnr/trace/mgmtlsnr.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/listener_scan1/trace/listener_scan1.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/asmnet1lsnr_asm/trace/asmnet1lsnr_asm_321.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/asmnet1lsnr_asm/trace/asmnet1lsnr_asm_325.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/apx/+apx/+APX2/trace/drc+APX2.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/asmtool/user_root/host_2670455502_107/trace/alert_+ASM2.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/clients/user_oracle/host_2670455502_107/trace/sqlnet.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/tnslsnr/rac02/listener_test/trace/listener_test.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/listener/trace/listener_193.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/start/trace/start.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/tnslsnr/rac02/asmnet1lsnr_asm/trace/asmnet1lsnr_asm.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/asmnet1lsnr_asm/trace/asmnet1lsnr_asm_322.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/asmnet1lsnr_asm/trace/asmnet1lsnr_asm_326.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/kfod/rac02/kfod/trace/alert_+ASM2.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/crs/rac02/crs/trace/alert.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/listener/trace/listener_194.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/tnslsnr/rac02/listener/trace/listener.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/clients/user_grid/host_2670455502_107/trace/sqlnet.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/tnslsnr/rac02/asmnet1lsnr_asm/trace/asmnet1lsnr_asm_323.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/rdbms/_mgmtdb/-MGMTDB/trace/alert_-MGMTDB.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/clients/user_grid/host_2670455502_82/trace/sqlnet.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/asmtool/user_root/host_2670455502_110/trace/alert.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/asmtool/user_grid/host_2670455502_107/trace/alert_+ASM2.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/clients/user_grid/host_2670455502_110/trace/sqlnet.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/rdbms/_mgmtdb/-MGMTDB/trace/drc-MGMTDB.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/apx/+apx/+APX2/trace/alert_+APX2.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/asm/+asm/+ASM2/trace/alert_+ASM2.log" 2022-11-18-6:0:0
"/u01/app/grid/diag/tnslsnr/rac02/asmnet1lsnr_asm/trace/asmnet1lsnr_asm_324.log" 2022-11-18-6:4:49
"/u01/app/grid/diag/asm/+asm/+ASM2/trace/drc+ASM2.log" 2022-11-18-6:0:0
[root@rac02 logrotate.d]#

Tuesday, 15 November 2022

How to execute some SQL in all Pluggable Databases (PDBs)

How to execute some SQL in all Pluggable Databases (PDBs)

How to execute some SQL in all Pluggable Databases (PDBs) http://anuj-singh.blogspot.com/2020_12_26_archive.html pwd /home/oracle statsinfo.sql cat statsinfo.sql set linesize 300 col OWNER for a20 col OBJECT_NAME for a28 col PARTITION_NAME for a20 col SUBPARTITION_NAME for a20 col GLOBAL_STATS for a15 col USER_STATS for a15 col TOTAL_COUNT for a35 col STALE_STATS for a15 SELECT 'Total Number of Stale Tables: '||COUNT(*) OVER() TOTAL_COUNT, OWNER, TABLE_NAME OBJECT_NAME, 'TABLE' OBJECT_TYPE, PARTITION_NAME, SUBPARTITION_NAME, LAST_ANALYZED, GLOBAL_STATS, USER_STATS, STATTYPE_LOCKED, STALE_STATS FROM DBA_TAB_STATISTICS WHERE STATTYPE_LOCKED IS NULL AND (STALE_STATS IS NULL OR STALE_STATS='YES') AND OWNER NOT IN ('GSMADMIN_INTERNAL','ANONYMOUS', 'CTXSYS', 'DBSNMP', 'EXFSYS','LBACSYS','MDSYS','MGMT_VIEW','OLAPSYS','OWBSYS','ORDPLUGINS','ORDSYS','OUTLN','SI_INFORMTN_SCHEMA','SYS', 'SYSMAN','SYSTEM','TSMSYS','WK_TEST','WKSYS','WKPROXY','WMSYS','XDB' ) AND OWNER NOT LIKE 'FLOW%' UNION ALL SELECT 'Total Number of Stale Indexes: '||COUNT(*) OVER() TOTAL_COUNT, OWNER, INDEX_NAME OBJECT_NAME, 'INDEX' OBJECT_TYPE, PARTITION_NAME, SUBPARTITION_NAME, LAST_ANALYZED, GLOBAL_STATS, USER_STATS, STATTYPE_LOCKED, STALE_STATS FROM DBA_IND_STATISTICS WHERE STATTYPE_LOCKED IS NULL AND (STALE_STATS IS NULL OR STALE_STATS='YES') AND OWNER NOT IN ('GSMADMIN_INTERNAL','ANONYMOUS', 'CTXSYS', 'DBSNMP', 'EXFSYS','LBACSYS','MDSYS','MGMT_VIEW','OLAPSYS','OWBSYS','ORDPLUGINS','ORDSYS','OUTLN','SI_INFORMTN_SCHEMA','SYS', 'SYSMAN','SYSTEM','TSMSYS','WK_TEST','WKSYS','WKPROXY','WMSYS','XDB' ) AND OWNER NOT LIKE 'FLOW%' / # Exclude PDB$SEED PDB9 containers (-C, --excl_con). -b" option is the prefix for the log file names. $ORACLE_HOME/perl/bin/perl $ORACLE_HOME/rdbms/admin/catcon.pl -n 1 -e -C 'PDB$SEED anujv' -b statsinfo statsinfo.sql $ORACLE_HOME/perl/bin/perl $ORACLE_HOME/rdbms/admin/catcon.pl -n 1 -e -C 'PDB$SEED anujv' -b statsinfo statsinfo.sql catcon: ALL catcon-related output will be written to [/home/oracle/statsinfo_catcon_26043.lst] catcon: See [/home/oracle/statsinfo*.log] files for output generated by scripts catcon: See [/home/oracle/statsinfo_*.lst] files for spool files, if any catcon.pl: completed successfully cat statsinfo0.log TOTAL_COUNT OWNER OBJECT_NAME OBJEC PARTITION_NAME SUBPARTITION_NAME LAST_ANALYZED GLOBAL_STATS USER_STATS STATT STALE_STATS ----------------------------------- -------------------- ---------------------------- ----- -------------------- -------------------- -------------- --------------- --------------- ----- --------------- Total Number of Stale Tables: 35 AUDSYS AUD$UNIFIED TABLE 31-08-21 01:00 YES NO YES Total Number of Stale Tables: 35 DVSYS DV$CMDCONTEXT TABLE NO NO Total Number of Stale Tables: 35 ORDDATA ORDDCM_CT_PRED_TMP TABLE NO NO Total Number of Stale Tables: 35 ORDDATA ORDDCM_RT_PREF_PARAMS_TMP TABLE NO NO Total Number of Stale Tables: 35 ORDDATA ORDDCM_ANON_ATTRS_TMP TABLE NO NO Total Number of Stale Tables: 35 ORDDATA ORDDCM_ANON_RULES_TMP TABLE NO NO Total Number of Stale Tables: 35 ORDDATA ORDDCM_STORED_TAGS_TMP TABLE NO NO ======================================= pwd /home/oracle <<<< location cat stats.sql <<<<< script !!!! exec dbms_stats.gather_schema_stats('SYS'); exec dbms_stats.gather_schema_stats('SYSTEM'); # Exclude PDB$SEED PDB9 containers (-C, --excl_con). -b" option is the prefix for the log file names. $ORACLE_HOME/perl/bin/perl $ORACLE_HOME/rdbms/admin/catcon.pl -n 1 -e -C 'PDB$SEED anujv' -b gatherstats stats.sql catcon: ALL catcon-related output will be written to [/home/oracle/gatherstats_catcon_12613.lst] catcon: See [/home/oracle/gatherstats*.log] files for output generated by scripts catcon: See [/home/oracle/gatherstats_*.lst] files for spool files, if any cat /home/oracle/gatherstats_catcon_12613.lst catcon: See [/home/oracle/gatherstats*.log] files for output generated by scripts catcon: See [/home/oracle/gatherstats_*.lst] files for spool files, if any !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! catcon version: /st_rdbms_12.2.0.1.0dbbp/2 catconInit: start logging catcon output at 2022-11-15 03:15:56 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! cat gatherstats0.log SQL*Plus: Release 12.2.0.1.0 Production on Tue Nov 15 03:15:57 2022 Copyright (c) 1982, 2016, Oracle. All rights reserved. idle sqlplus> Connected. primary:sys@vihcdbd8-vihcdbd8 sqlplus> 2 Session altered. primary:sys@vihcdbd8-vihcdbd8 sqlplus> 2 Session altered. primary:sys@vihcdbd8-vihcdbd8 sqlplus> ALTER SYSTEM KILL SESSION '394,26285' force timeout 0 -- process 12665 / primary:sys@vihcdbd8-vihcdbd8 sqlplus> primary:sys@vihcdbd8-vihcdbd8 sqlplus> 2 Session altered. primary:sys@vihcdbd8-vihcdbd8 sqlplus> 2 Session altered. primary:sys@vihcdbd8-vihcdbd8 sqlplus> primary:sys@vihcdbd8-vihcdbd8 sqlplus> primary:sys@vihcdbd8-vihcdbd8 sqlplus> 2 Session altered. primary:sys@vihcdbd8-vihcdbd8 sqlplus> NOW_CONNECTED_TO ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ==== Current Container = CDB$ROOT Id = 1 ==== primary:sys@vihcdbd8-vihcdbd8 sqlplus> NOW_CONNECTED_TO ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ==== Current Container = CDB$ROOT Id = 1 ==== primary:sys@vihcdbd8-vihcdbd8 sqlplus> 2 Session altered. CATCONSECTION -------------------------- ==== CATCON EXEC ROOT ==== SQL> BEGIN_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:CDB$ROOT Id:1 22-11-15 03:15:57 Proc:0 ==== SQL> BEGIN_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:CDB$ROOT Id:1 22-11-15 03:15:57 Proc:0 ==== SQL> 2 Session altered. SQL> 2 Session altered. SQL> SQL> exec dbms_stats.gather_schema_stats('SYS'); PL/SQL procedure successfully completed. SQL> exec dbms_stats.gather_schema_stats('SYSTEM'); PL/SQL procedure successfully completed. SQL> END_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:CDB$ROOT Id:1 22-11-15 03:19:05 Proc:0 ==== SQL> END_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:CDB$ROOT Id:1 22-11-15 03:19:05 Proc:0 ==== SQL> SQL> SQL> 2 Session altered. SQL> SQL> SQL> 2 Session altered. Session altered. SQL> NOW_CONNECTED_TO -------------------------------------------------------------------------------- ==== Current Container = PDB9 Id = 3 ==== SQL> NOW_CONNECTED_TO -------------------------------------------------------------------------------- ==== Current Container = PDB9 Id = 3 ==== SQL> SQL> 2 CATCONSECTION ----------------------------------- ==== CATCON EXEC IN CONTAINERS ==== SQL> BEGIN_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:PDB9 Id:3 22-11-15 03:19:05 Proc:0 ==== SQL> BEGIN_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:PDB9 Id:3 22-11-15 03:19:05 Proc:0 ==== SQL> 2 Session altered. SQL> 2 Session altered. SQL> SQL> exec dbms_stats.gather_schema_stats('SYS'); PL/SQL procedure successfully completed. SQL> exec dbms_stats.gather_schema_stats('SYSTEM'); PL/SQL procedure successfully completed. SQL> END_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:PDB9 Id:3 22-11-15 03:21:46 Proc:0 ==== SQL> END_RUNNING -------------------------------------------------------------------------------- ==== @stats.sql Container:PDB9 Id:3 22-11-15 03:21:46 Proc:0 ==== SQL> SQL> SQL> 2 Session altered. SQL> SQL> SQL> ========== PROCESS ENDED ========== SQL> Disconnected from Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production [oracle@ibrac02 ~]$ ============================================================================================================================= via plsql !!!! How to execute some SQL in all Pluggable Databases (PDBs) https://carlos-sierra.net/2017/07/03/how-to-execute-some-sql-in-all-pluggable-databases-pdbs/ COL report_date NEW_V report_date; SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD"T"HH24-MI-SS') report_date FROM DUAL; SPO /tmp/change_all_pdbs_&&report_date..txt; VAR v_cursor CLOB; BEGIN :v_cursor := q'[ DECLARE PRAGMA AUTONOMOUS_TRANSACTION; BEGIN DBMS_OUTPUT.PUT_LINE('ENABLE DBMS_AUTO_TASK_ADMIN'); DBMS_AUTO_TASK_ADMIN.ENABLE; FOR i IN (SELECT client_name, operation_name FROM dba_autotask_operation WHERE status = 'DISABLED' ORDER BY 1, 2) LOOP DBMS_OUTPUT.PUT_LINE('ENABLE CLIENT_NAME:'||i.client_name||' OPERATION:'||i.operation_name); DBMS_AUTO_TASK_ADMIN.ENABLE ( client_name => i.client_name , operation => NULL , window_name => NULL ); END LOOP; COMMIT; END; ]'; END; / PRINT v_cursor; SET SERVEROUTPUT ON DECLARE l_cursor_id INTEGER; l_rows_processed INTEGER; BEGIN l_cursor_id := DBMS_SQL.OPEN_CURSOR; FOR i IN (SELECT name FROM v$containers WHERE con_id > 2 AND open_mode = 'READ WRITE' ORDER BY 1) LOOP DBMS_OUTPUT.PUT_LINE('PDB:'||i.name); DBMS_SQL.PARSE ( c => l_cursor_id , statement => :v_cursor , language_flag => DBMS_SQL.NATIVE , container => i.name ); l_rows_processed := DBMS_SQL.EXECUTE(c => l_cursor_id); END LOOP; DBMS_SQL.CLOSE_CURSOR(c => l_cursor_id); END; / SPO OFF;

Monday, 14 November 2022

SQL Profile Script

 SQL Profile Script 




Encouraging CBO to Pickup a Better Execution Plan Using the COE XFR SQL Profile Script (Doc ID 1955195.1)



var sqlid varchar2(30)
 begin :sqlid := '87gaftwrm2h68'; end;  ---- sql id name here!!!!
/



select 'exec sys.dbms_shared_pool.purge('''||address||', '||hash_value||''', ''c'')'
from gv$sql
where sql_id = :sqlid
--and child_number=&childnr
;

Value        Kind of Object to keep
--        -----        ----------------------
--          P          package/procedure/function
--          Q          sequence
--          R          trigger
--          T          type
--          JS         java source
--          JC         java class
--          JR         java resource
--          JD         java shared data
--          C          cursor



select ADDRESS, HASH_VALUE from V$SQLAREA where SQL_ID='251fjyn5fj84q';
exec DBMS_SHARED_POOL.PURGE ('00000005DGEC9DE0, 257655674', 'C');



set verify off
set pagesize 999
col username format a13
col prog format a22
col sql_text format a41
col sid format 999
col child_number format 99999 heading CHILD
col ocategory format a10
col avg_etime format 9,999,999.99
col etime format 9,999,999.99

select sql_id, child_number, plan_hash_value plan_hash, executions execs, elapsed_time/1000000 etime,(elapsed_time/1000000)/decode(nvl(executions,0),0,1,executions) avg_etime, u.username,
sql_text
from gv$sql s, dba_users u
where upper(sql_text) like upper(nvl('&sql_text',sql_text))
and sql_text not like '%from v$sql where sql_text like nvl(%'
and sql_id like nvl(':sqlid',sql_id)
and u.user_id = s.parsing_user_id
/








select sql_id,  count(distinct plan_hash_value) distinct_plans, sql_text from gv$sql
group by sql_id, sql_text
having count(distinct plan_hash_value) >= &how_many
/



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

@coe_xfr_sql_profile.sql dkz7v96ym42c6 3302976337 



Correcting Optimizer Cost Estimates to Encourage Good Execution Plans Using the COE XFR SQL Profile Script (Doc ID 1955195.1)



SPO coe_xfr_sql_profile.log;
SET DEF ON TERM OFF ECHO ON FEED OFF VER OFF HEA ON LIN 2000 PAGES 100 LONG 8000000 LONGC 800000 TRIMS ON TI OFF TIMI OFF SERVEROUT ON SIZE 1000000 NUMF "" SQLP SQL>;
SET SERVEROUT ON SIZE UNL;
REM
REM $Header: 215187.1 coe_xfr_sql_profile.sql 11.4.5.5 2013/03/01 carlos.sierra $
REM
REM Copyright (c) 2000-2013, Oracle Corporation. All rights reserved.
REM
REM AUTHOR
REM   carlos.sierra@oracle.com
REM
REM SCRIPT
REM   coe_xfr_sql_profile.sql
REM
REM DESCRIPTION
REM   This script generates another that contains the commands to
REM   create a manual custom SQL Profile out of a known plan from
REM   memory or AWR. The manual custom profile can be implemented
REM   into the same SOURCE system where the plan was retrieved,
REM   or into another similar TARGET system that has same schema
REM   objects referenced by the SQL that generated the known plan.
REM
REM PRE-REQUISITES
REM   1. Oracle Tuning Pack license.
REM
REM PARAMETERS
REM   1. SQL_ID (required)
REM   2. Plan Hash Value for which a manual custom SQL Profile is
REM      needed (required). A list of known plans is presented.
REM      You may choose from list provided or enter a valid phv
REM      from a version of the SQL modified with Hints.
REM
REM EXECUTION
REM   1. Connect into SQL*Plus as user with access to data dictionary.
REM      Do not use SYS.
REM   2. Execute script coe_xfr_sql_profile.sql passing SQL_ID and
REM      plan hash value (parameters can be passed inline or until
REM      requested).
REM
REM EXAMPLE
REM   # sqlplus system
REM   SQL> START coe_xfr_sql_profile.sql [SQL_ID] [PLAN_HASH_VALUE];
REM   SQL> START coe_xfr_sql_profile.sql gnjy0mn4y9pbm 2055843663;
REM   SQL> START coe_xfr_sql_profile.sql gnjy0mn4y9pbm;
REM   SQL> START coe_xfr_sql_profile.sql;
REM
REM NOTES
REM   1. For possible errors see coe_xfr_sql_profile.log
REM   2. If SQLT is installed in SOURCE, you can use instead:
REM      sqlt/utl/sqltprofile.sql
REM   3. Be aware that using DBMS_SQLTUNE requires a license for
REM      Oracle Tuning Pack.
REM   4. Use a DBA user but not SYS.
REM
SET TERM ON ECHO OFF;
PRO
PRO Parameter 1:
PRO SQL_ID (required)
PRO
DEF sql_id = '&1';
PRO
WITH
p AS (
SELECT plan_hash_value
  FROM gv$sql_plan
 WHERE sql_id = TRIM('&&sql_id.')
   AND other_xml IS NOT NULL
 UNION
SELECT plan_hash_value
  FROM dba_hist_sql_plan
 WHERE sql_id = TRIM('&&sql_id.')
   AND other_xml IS NOT NULL ),
m AS (
SELECT plan_hash_value,
       SUM(elapsed_time)/SUM(executions) avg_et_secs
  FROM gv$sql
 WHERE sql_id = TRIM('&&sql_id.')
   AND executions > 0
 GROUP BY
       plan_hash_value ),
a AS (
SELECT plan_hash_value,
       SUM(elapsed_time_total)/SUM(executions_total) avg_et_secs
  FROM dba_hist_sqlstat
 WHERE sql_id = TRIM('&&sql_id.')
   AND executions_total > 0
 GROUP BY
       plan_hash_value )
SELECT p.plan_hash_value,
       ROUND(NVL(m.avg_et_secs, a.avg_et_secs)/1e6, 3) avg_et_secs
  FROM p, m, a
 WHERE p.plan_hash_value = m.plan_hash_value(+)
   AND p.plan_hash_value = a.plan_hash_value(+)
 ORDER BY
       avg_et_secs NULLS LAST;
PRO
PRO Parameter 2:
PRO PLAN_HASH_VALUE (required)
PRO
DEF plan_hash_value = '&2';
PRO
PRO Values passed to coe_xfr_sql_profile:
PRO ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PRO SQL_ID         : "&&sql_id."
PRO PLAN_HASH_VALUE: "&&plan_hash_value."
PRO
SET TERM OFF ECHO ON;
WHENEVER SQLERROR EXIT SQL.SQLCODE;

-- trim parameters
COL sql_id NEW_V sql_id FOR A30;
COL plan_hash_value NEW_V plan_hash_value FOR A30;
SELECT TRIM('&&sql_id.') sql_id, TRIM('&&plan_hash_value.') plan_hash_value FROM DUAL;

VAR sql_text CLOB;
VAR sql_text2 CLOB;
VAR other_xml CLOB;
EXEC :sql_text := NULL;
EXEC :sql_text2 := NULL;
EXEC :other_xml := NULL;

-- get sql_text from memory
DECLARE
  l_sql_text VARCHAR2(32767);
BEGIN -- 10g see bug 5017909
  FOR i IN (SELECT DISTINCT piece, sql_text
              FROM gv$sqltext_with_newlines
             WHERE sql_id = TRIM('&&sql_id.')
             ORDER BY 1, 2)
  LOOP
    IF :sql_text IS NULL THEN
      DBMS_LOB.CREATETEMPORARY(:sql_text, TRUE);
      DBMS_LOB.OPEN(:sql_text, DBMS_LOB.LOB_READWRITE);
    END IF;
    -- removes NUL characters
    l_sql_text := REPLACE(i.sql_text, CHR(00), ' ');
    -- adds a NUL character at the end of each line
    DBMS_LOB.WRITEAPPEND(:sql_text, LENGTH(l_sql_text) + 1, l_sql_text||CHR(00));
  END LOOP;
  -- if found in memory then sql_text is not null
  IF :sql_text IS NOT NULL THEN
    DBMS_LOB.CLOSE(:sql_text);
  END IF;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('getting sql_text from memory: '||SQLERRM);
    :sql_text := NULL;
END;
/

SELECT :sql_text FROM DUAL;

-- get sql_text from awr
DECLARE
  l_sql_text VARCHAR2(32767);
  l_clob_size NUMBER;
  l_offset NUMBER;
BEGIN
  IF :sql_text IS NULL OR NVL(DBMS_LOB.GETLENGTH(:sql_text), 0) = 0 THEN
    SELECT sql_text
      INTO :sql_text2
      FROM dba_hist_sqltext
     WHERE sql_id = TRIM('&&sql_id.')
       AND sql_text IS NOT NULL
       AND ROWNUM = 1;
  END IF;
  -- if found in awr then sql_text2 is not null
  IF :sql_text2 IS NOT NULL THEN
    l_clob_size := NVL(DBMS_LOB.GETLENGTH(:sql_text2), 0);
    l_offset := 1;
    DBMS_LOB.CREATETEMPORARY(:sql_text, TRUE);
    DBMS_LOB.OPEN(:sql_text, DBMS_LOB.LOB_READWRITE);
    -- store in clob as 64 character pieces plus a NUL character at the end of each piece
    WHILE l_offset < l_clob_size
    LOOP
      IF l_clob_size - l_offset > 64 THEN
        l_sql_text := REPLACE(DBMS_LOB.SUBSTR(:sql_text2, 64, l_offset), CHR(00), ' ');
      ELSE -- last piece
        l_sql_text := REPLACE(DBMS_LOB.SUBSTR(:sql_text2, l_clob_size - l_offset + 1, l_offset), CHR(00), ' ');
      END IF;
      DBMS_LOB.WRITEAPPEND(:sql_text, LENGTH(l_sql_text) + 1, l_sql_text||CHR(00));
      l_offset := l_offset + 64;
    END LOOP;
    DBMS_LOB.CLOSE(:sql_text);
  END IF;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('getting sql_text from awr: '||SQLERRM);
    :sql_text := NULL;
END;
/

SELECT :sql_text2 FROM DUAL;
SELECT :sql_text FROM DUAL;

-- validate sql_text
SET TERM ON;
BEGIN
  IF :sql_text IS NULL THEN
    RAISE_APPLICATION_ERROR(-20100, 'SQL_TEXT for SQL_ID &&sql_id. was not found in memory (gv$sqltext_with_newlines) or AWR (dba_hist_sqltext).');
  END IF;
END;
/
SET TERM OFF;

-- get other_xml from memory
BEGIN
  FOR i IN (SELECT other_xml
              FROM gv$sql_plan
             WHERE sql_id = TRIM('&&sql_id.')
               AND plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
               AND other_xml IS NOT NULL
             ORDER BY
                   child_number, id)
  LOOP
    :other_xml := i.other_xml;
    EXIT; -- 1st
  END LOOP;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('getting other_xml from memory: '||SQLERRM);
    :other_xml := NULL;
END;
/

-- get other_xml from awr
BEGIN
  IF :other_xml IS NULL OR NVL(DBMS_LOB.GETLENGTH(:other_xml), 0) = 0 THEN
    FOR i IN (SELECT other_xml
                FROM dba_hist_sql_plan
               WHERE sql_id = TRIM('&&sql_id.')
                 AND plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
                 AND other_xml IS NOT NULL
               ORDER BY
                     id)
    LOOP
      :other_xml := i.other_xml;
      EXIT; -- 1st
    END LOOP;
  END IF;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('getting other_xml from awr: '||SQLERRM);
    :other_xml := NULL;
END;
/

-- get other_xml from memory from modified SQL
BEGIN
  IF :other_xml IS NULL OR NVL(DBMS_LOB.GETLENGTH(:other_xml), 0) = 0 THEN
    FOR i IN (SELECT other_xml
                FROM gv$sql_plan
               WHERE plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
                 AND other_xml IS NOT NULL
               ORDER BY
                     child_number, id)
    LOOP
      :other_xml := i.other_xml;
      EXIT; -- 1st
    END LOOP;
  END IF;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('getting other_xml from memory: '||SQLERRM);
    :other_xml := NULL;
END;
/

-- get other_xml from awr from modified SQL
BEGIN
  IF :other_xml IS NULL OR NVL(DBMS_LOB.GETLENGTH(:other_xml), 0) = 0 THEN
    FOR i IN (SELECT other_xml
                FROM dba_hist_sql_plan
               WHERE plan_hash_value = TO_NUMBER(TRIM('&&plan_hash_value.'))
                 AND other_xml IS NOT NULL
               ORDER BY
                     id)
    LOOP
      :other_xml := i.other_xml;
      EXIT; -- 1st
    END LOOP;
  END IF;
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('getting other_xml from awr: '||SQLERRM);
    :other_xml := NULL;
END;
/

SELECT :other_xml FROM DUAL;

-- validate other_xml
SET TERM ON;
BEGIN
  IF :other_xml IS NULL THEN
    RAISE_APPLICATION_ERROR(-20101, 'PLAN for SQL_ID &&sql_id. and PHV &&plan_hash_value. was not found in memory (gv$sql_plan) or AWR (dba_hist_sql_plan).');
  END IF;
END;
/
SET TERM OFF;

-- generates script that creates sql profile in target system:
SET ECHO OFF;
PRO coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql.
SET FEED OFF LIN 666 TRIMS ON TI OFF TIMI OFF SERVEROUT ON SIZE 1000000 FOR WOR;
SET SERVEROUT ON SIZE UNL FOR WOR;
SPO OFF;
SPO coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql;
DECLARE
  l_pos NUMBER;
  l_clob_size NUMBER;
  l_offset NUMBER;
  l_sql_text VARCHAR2(32767);
  l_len NUMBER;
  l_hint VARCHAR2(32767);
BEGIN
  DBMS_OUTPUT.PUT_LINE('SPO coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..log;');
  DBMS_OUTPUT.PUT_LINE('SET ECHO ON TERM ON LIN 2000 TRIMS ON NUMF 99999999999999999999;');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM $Header: 215187.1 coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql 11.4.4.4 '||TO_CHAR(SYSDATE, 'YYYY/MM/DD')||' carlos.sierra $');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM Copyright (c) 2000-2012, Oracle Corporation. All rights reserved.');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM AUTHOR');
  DBMS_OUTPUT.PUT_LINE('REM   carlos.sierra@oracle.com');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM SCRIPT');
  DBMS_OUTPUT.PUT_LINE('REM   coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM DESCRIPTION');
  DBMS_OUTPUT.PUT_LINE('REM   This script is generated by coe_xfr_sql_profile.sql');
  DBMS_OUTPUT.PUT_LINE('REM   It contains the SQL*Plus commands to create a custom');
  DBMS_OUTPUT.PUT_LINE('REM   SQL Profile for SQL_ID &&sql_id. based on plan hash');
  DBMS_OUTPUT.PUT_LINE('REM   value &&plan_hash_value..');
  DBMS_OUTPUT.PUT_LINE('REM   The custom SQL Profile to be created by this script');
  DBMS_OUTPUT.PUT_LINE('REM   will affect plans for SQL commands with signature');
  DBMS_OUTPUT.PUT_LINE('REM   matching the one for SQL Text below.');
  DBMS_OUTPUT.PUT_LINE('REM   Review SQL Text and adjust accordingly.');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM PARAMETERS');
  DBMS_OUTPUT.PUT_LINE('REM   None.');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM EXAMPLE');
  DBMS_OUTPUT.PUT_LINE('REM   SQL> START coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql;');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('REM NOTES');
  DBMS_OUTPUT.PUT_LINE('REM   1. Should be run as SYSTEM or SYSDBA.');
  DBMS_OUTPUT.PUT_LINE('REM   2. User must have CREATE ANY SQL PROFILE privilege.');
  DBMS_OUTPUT.PUT_LINE('REM   3. SOURCE and TARGET systems can be the same or similar.');
  DBMS_OUTPUT.PUT_LINE('REM   4. To drop this custom SQL Profile after it has been created:');
  DBMS_OUTPUT.PUT_LINE('REM      EXEC DBMS_SQLTUNE.DROP_SQL_PROFILE(''coe_&&sql_id._&&plan_hash_value.'');');
  DBMS_OUTPUT.PUT_LINE('REM   5. Be aware that using DBMS_SQLTUNE requires a license');
  DBMS_OUTPUT.PUT_LINE('REM      for the Oracle Tuning Pack.');
  DBMS_OUTPUT.PUT_LINE('REM   6. If you modified a SQL putting Hints in order to produce a desired');
  DBMS_OUTPUT.PUT_LINE('REM      Plan, you can remove the artifical Hints from SQL Text pieces below.');
  DBMS_OUTPUT.PUT_LINE('REM      By doing so you can create a custom SQL Profile for the original');
  DBMS_OUTPUT.PUT_LINE('REM      SQL but with the Plan captured from the modified SQL (with Hints).');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('WHENEVER SQLERROR EXIT SQL.SQLCODE;');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('VAR signature NUMBER;');
  DBMS_OUTPUT.PUT_LINE('VAR signaturef NUMBER;');
  DBMS_OUTPUT.PUT_LINE('REM');
  DBMS_OUTPUT.PUT_LINE('DECLARE');
  DBMS_OUTPUT.PUT_LINE('sql_txt CLOB;');
  DBMS_OUTPUT.PUT_LINE('h       SYS.SQLPROF_ATTR;');
  DBMS_OUTPUT.PUT_LINE('PROCEDURE wa (p_line IN VARCHAR2) IS');
  DBMS_OUTPUT.PUT_LINE('BEGIN');
  DBMS_OUTPUT.PUT_LINE('DBMS_LOB.WRITEAPPEND(sql_txt, LENGTH(p_line), p_line);');
  DBMS_OUTPUT.PUT_LINE('END wa;');
  DBMS_OUTPUT.PUT_LINE('BEGIN');
  DBMS_OUTPUT.PUT_LINE('DBMS_LOB.CREATETEMPORARY(sql_txt, TRUE);');
  DBMS_OUTPUT.PUT_LINE('DBMS_LOB.OPEN(sql_txt, DBMS_LOB.LOB_READWRITE);');
  DBMS_OUTPUT.PUT_LINE('-- SQL Text pieces below do not have to be of same length.');
  DBMS_OUTPUT.PUT_LINE('-- So if you edit SQL Text (i.e. removing temporary Hints),');
  DBMS_OUTPUT.PUT_LINE('-- there is no need to edit or re-align unmodified pieces.');
  l_clob_size := NVL(DBMS_LOB.GETLENGTH(:sql_text), 0);
  l_offset := 1;
  WHILE l_offset < l_clob_size
  LOOP
    l_pos := DBMS_LOB.INSTR(:sql_text, CHR(00), l_offset);
    IF l_pos > 0 THEN
      l_len := l_pos - l_offset;
    ELSE -- last piece
      l_len := l_clob_size - l_pos + 1;
    END IF;
    l_sql_text := DBMS_LOB.SUBSTR(:sql_text, l_len, l_offset);
    /* cannot do such 3 replacement since a line could end with a comment using "--"
    l_sql_text := REPLACE(l_sql_text, CHR(10), ' '); -- replace LF with SP
    l_sql_text := REPLACE(l_sql_text, CHR(13), ' '); -- replace CR with SP
    l_sql_text := REPLACE(l_sql_text, CHR(09), ' '); -- replace TAB with SP
    */
    l_offset := l_offset + l_len + 1;
    IF l_len > 0 THEN
      IF INSTR(l_sql_text, '''[') + INSTR(l_sql_text, ']''') = 0 THEN
        l_sql_text := '['||l_sql_text||']';
      ELSIF INSTR(l_sql_text, '''{') + INSTR(l_sql_text, '}''') = 0 THEN
        l_sql_text := '{'||l_sql_text||'}';
      ELSIF INSTR(l_sql_text, '''<') + INSTR(l_sql_text, '>''') = 0 THEN
        l_sql_text := '<'||l_sql_text||'>';
      ELSIF INSTR(l_sql_text, '''(') + INSTR(l_sql_text, ')''') = 0 THEN
        l_sql_text := '('||l_sql_text||')';
      ELSIF INSTR(l_sql_text, '''"') + INSTR(l_sql_text, '"''') = 0 THEN
        l_sql_text := '"'||l_sql_text||'"';
      ELSIF INSTR(l_sql_text, '''|') + INSTR(l_sql_text, '|''') = 0 THEN
        l_sql_text := '|'||l_sql_text||'|';
      ELSIF INSTR(l_sql_text, '''~') + INSTR(l_sql_text, '~''') = 0 THEN
        l_sql_text := '~'||l_sql_text||'~';
      ELSIF INSTR(l_sql_text, '''^') + INSTR(l_sql_text, '^''') = 0 THEN
        l_sql_text := '^'||l_sql_text||'^';
      ELSIF INSTR(l_sql_text, '''@') + INSTR(l_sql_text, '@''') = 0 THEN
        l_sql_text := '@'||l_sql_text||'@';
      ELSIF INSTR(l_sql_text, '''#') + INSTR(l_sql_text, '#''') = 0 THEN
        l_sql_text := '#'||l_sql_text||'#';
      ELSIF INSTR(l_sql_text, '''%') + INSTR(l_sql_text, '%''') = 0 THEN
        l_sql_text := '%'||l_sql_text||'%';
      ELSIF INSTR(l_sql_text, '''$') + INSTR(l_sql_text, '$''') = 0 THEN
        l_sql_text := '$'||l_sql_text||'$';
      ELSE
        l_sql_text := CHR(96)||l_sql_text||CHR(96);
      END IF;
      DBMS_OUTPUT.PUT_LINE('wa(q'''||l_sql_text||''');');
    END IF;
  END LOOP;
  DBMS_OUTPUT.PUT_LINE('DBMS_LOB.CLOSE(sql_txt);');
  DBMS_OUTPUT.PUT_LINE('h := SYS.SQLPROF_ATTR(');
  DBMS_OUTPUT.PUT_LINE('q''[BEGIN_OUTLINE_DATA]'',');
  FOR i IN (SELECT /*+ opt_param('parallel_execution_enabled', 'false') */
                   SUBSTR(EXTRACTVALUE(VALUE(d), '/hint'), 1, 4000) hint
              FROM TABLE(XMLSEQUENCE(EXTRACT(XMLTYPE(:other_xml), '/*/outline_data/hint'))) d)
  LOOP
    l_hint := i.hint;
    WHILE NVL(LENGTH(l_hint), 0) > 0
    LOOP
      IF LENGTH(l_hint) <= 500 THEN
        DBMS_OUTPUT.PUT_LINE('q''['||l_hint||']'',');
        l_hint := NULL;
      ELSE
        l_pos := INSTR(SUBSTR(l_hint, 1, 500), ' ', -1);
        DBMS_OUTPUT.PUT_LINE('q''['||SUBSTR(l_hint, 1, l_pos)||']'',');
        l_hint := '   '||SUBSTR(l_hint, l_pos);
      END IF;
    END LOOP;
  END LOOP;
  DBMS_OUTPUT.PUT_LINE('q''[END_OUTLINE_DATA]'');');
  DBMS_OUTPUT.PUT_LINE(':signature := DBMS_SQLTUNE.SQLTEXT_TO_SIGNATURE(sql_txt);');
  DBMS_OUTPUT.PUT_LINE(':signaturef := DBMS_SQLTUNE.SQLTEXT_TO_SIGNATURE(sql_txt, TRUE);');
  DBMS_OUTPUT.PUT_LINE('DBMS_SQLTUNE.IMPORT_SQL_PROFILE (');
  DBMS_OUTPUT.PUT_LINE('sql_text    => sql_txt,');
  DBMS_OUTPUT.PUT_LINE('profile     => h,');
  DBMS_OUTPUT.PUT_LINE('name        => ''coe_&&sql_id._&&plan_hash_value.'',');
  DBMS_OUTPUT.PUT_LINE('description => ''coe &&sql_id. &&plan_hash_value. ''||:signature||'' ''||:signaturef||'''',');
  DBMS_OUTPUT.PUT_LINE('category    => ''DEFAULT'',');
  DBMS_OUTPUT.PUT_LINE('validate    => TRUE,');
  DBMS_OUTPUT.PUT_LINE('replace     => TRUE,');
  DBMS_OUTPUT.PUT_LINE('force_match => FALSE /* TRUE:FORCE (match even when different literals in SQL). FALSE:EXACT (similar to CURSOR_SHARING) */ );');
  DBMS_OUTPUT.PUT_LINE('DBMS_LOB.FREETEMPORARY(sql_txt);');
  DBMS_OUTPUT.PUT_LINE('END;');
  DBMS_OUTPUT.PUT_LINE('/');
  DBMS_OUTPUT.PUT_LINE('WHENEVER SQLERROR CONTINUE');
  DBMS_OUTPUT.PUT_LINE('SET ECHO OFF;');
  DBMS_OUTPUT.PUT_LINE('PRINT signature');
  DBMS_OUTPUT.PUT_LINE('PRINT signaturef');
  DBMS_OUTPUT.PUT_LINE('PRO');
  DBMS_OUTPUT.PUT_LINE('PRO ... manual custom SQL Profile has been created');
  DBMS_OUTPUT.PUT_LINE('PRO');
  DBMS_OUTPUT.PUT_LINE('SET TERM ON ECHO OFF LIN 80 TRIMS OFF NUMF "";');
  DBMS_OUTPUT.PUT_LINE('SPO OFF;');
  DBMS_OUTPUT.PUT_LINE('PRO');
  DBMS_OUTPUT.PUT_LINE('PRO COE_XFR_SQL_PROFILE_&&sql_id._&&plan_hash_value. completed');
END;
/
SPO OFF;
SET DEF ON TERM ON ECHO OFF FEED 6 VER ON HEA ON LIN 80 PAGES 14 LONG 80 LONGC 80 TRIMS OFF TI OFF TIMI OFF SERVEROUT OFF NUMF "" SQLP SQL>;
SET SERVEROUT OFF;
PRO
PRO Execute coe_xfr_sql_profile_&&sql_id._&&plan_hash_value..sql
PRO on TARGET system in order to create a custom SQL Profile
PRO with plan &&plan_hash_value linked to adjusted sql_text.
PRO
UNDEFINE 1 2 sql_id plan_hash_value
CL COL
PRO
PRO COE_XFR_SQL_PROFILE completed.


=====

Sunday, 13 November 2022

How To Fix the Best Plan from Cursor Cache in Oracle

How To Fix The Best Plan From Cursor Cache in Oracle



How to Get SQL_HANDLE And PLAN_NAME From DBA_SQL_PLAN_BASELINES (Doc ID 2242868.1)


http://anuj-singh.blogspot.com/2011/07/oracle-11g-baseline.html

Oracle version .. 
SQL> def
DEFINE _DATE           = "13-NOV-22" (CHAR)
DEFINE _CONNECT_IDENTIFIER = "rac1" (CHAR)
DEFINE _USER           = "SYS" (CHAR)
DEFINE _PRIVILEGE      = "AS SYSDBA" (CHAR)
DEFINE _SQLPLUS_RELEASE = "1202000100" (CHAR)


How to Get SQL_HANDLE And PLAN_NAME From DBA_SQL_PLAN_BASELINES (Doc ID 2242868.1)


http://anuj-singh.blogspot.com/2011/07/oracle-11g-baseline.html

SQL> def
DEFINE _DATE           = "13-NOV-22" (CHAR)
DEFINE _CONNECT_IDENTIFIER = "rac1" (CHAR)
DEFINE _USER           = "SYS" (CHAR)
DEFINE _PRIVILEGE      = "AS SYSDBA" (CHAR)
DEFINE _SQLPLUS_RELEASE = "1202000100" (CHAR)



should be true 

 show parameter OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
optimizer_capture_sql_plan_baselines boolean     FALSE


 ALTER SYSTEM SET OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES=true;



 show parameter OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
optimizer_capture_sql_plan_baselines boolean     TRUE
SQL>





var ENAME varchar2(10)
 begin :ENAME := 'ALLEN'; end;
/

 select * from emp where ENAME=:ENAME ;
 
  EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600        300         30


aim to fix above sql 




col sql_text for a50 wrap
col SQL_PLAN_BASELINE for a35
select sql_id, plan_hash_value, exact_matching_signature, sql_plan_baseline,sql_text
  from gv$sql
 where lower(sql_text) like lower('%select * from emp where ENAME=:ENAME%')
     --  and command_type = 3
   and sql_text not like '%from gv$sql%';



SQL_ID          PLAN_HASH_VALUE EXACT_MATCHING_SIGNATURE SQL_PLAN_BASELINE                   SQL_TEXT
------------- ----------------- ------------------------ ----------------------------------- --------------------------------------------------
7j5bb53huv8v1        3956160932     11343619050667859858 SQL_PLAN_9uv51dmr6krwkd8a279cc      select * from emp where ENAME=:ENAME


COLUMN sql_text FORMAT A120
COLUMN sql_id FORMAT A13
COLUMN bind_name FORMAT A10
COLUMN bind_value FORMAT A26
SELECT sql_id, b.LAST_CAPTURED,
b.HASH_VALUE, b.name bind_name, b.value_string bind_value, t.sql_text sql_text,
FROM
gv$sql t JOIN gv$sql_bind_capture b using (sql_id)
WHERE b.value_string is not null
AND sql_id='&sqlid';


select * from table(dbms_xplan.display_cursor('&sqlid',0, format => 'TYPICAL +PEEKED_BINDS'));



 VARIABLE cnt NUMBER
EXECUTE :cnt := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE( sql_id => '7j5bb53huv8v1',plan_hash_value => '3956160932');
 




before !!
col sql_text for a50 wrap
col enabled for a15
col  accepted for a15
col fixed for a15
col CREATED for a30
select CREATED,sql_handle, plan_name, sql_text, enabled, accepted, fixed from dba_sql_plan_baselines
where 1=1
and CREATED >sysdate - interval '1' hour;

CREATED                        SQL_HANDLE           PLAN_NAME                      SQL_TEXT                                           ENABLED         ACCEPTED        FIXED
------------------------------ -------------------- ------------------------------ -------------------------------------------------- --------------- --------------- ---------------
13-NOV-22 12.17.02.000000 PM   SQL_9d6ca16cee695f92 SQL_PLAN_9uv51dmr6krwkd8a279cc select * from emp where ENAME=:ENAME               YES             YES             NO




define sql_id='7j5bb53huv8v1'

SELECT PLAN_TABLE_OUTPUT
FROM V$SQL s, DBA_SQL_PLAN_BASELINES b, 
TABLE(
DBMS_XPLAN.DISPLAY_SQL_PLAN_BASELINE(b.sql_handle,b.plan_name,'basic') 
) t
WHERE s.EXACT_MATCHING_SIGNATURE=b.SIGNATURE
AND b.PLAN_NAME=s.SQL_PLAN_BASELINE
AND s.SQL_ID='&sql_id';


PLAN_TABLE_OUTPUT
----------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------
SQL handle: SQL_9d6ca16cee695f92
SQL text: select * from emp where ENAME=:ENAME
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
Plan name: SQL_PLAN_9uv51dmr6krwkd8a279cc         Plan id: 3634526668
Enabled: YES     Fixed: YES     Accepted: YES     Origin: MANUAL-LOAD-FROM-CURSOR-CACHE
Plan rows: From dictionary
--------------------------------------------------------------------------------

Plan hash value: 3956160932

----------------------------------
| Id  | Operation         | Name |
----------------------------------
|   0 | SELECT STATEMENT  |      |
|   1 |  TABLE ACCESS FULL| EMP  |
----------------------------------





col PLAN_TABLE_OUTPUT for a100
select * from table (DBMS_XPLAN.DISPLAY_SQL_PLAN_BASELINE('SQL_9d6ca16cee695f92', format=>'+adaptive'));


 SQL> SQL>
PLAN_TABLE_OUTPUT
----------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------
SQL handle: SQL_9d6ca16cee695f92
SQL text: select * from emp where ENAME=:ENAME
--------------------------------------------------------------------------------

--------------------------------------------------------------------------------
Plan name: SQL_PLAN_9uv51dmr6krwkd8a279cc         Plan id: 3634526668
Enabled: YES     Fixed: NO      Accepted: YES     Origin: MANUAL-LOAD-FROM-CURSOR-CACHE
Plan rows: From dictionary
--------------------------------------------------------------------------------

Plan hash value: 3956160932

--------------------------------------------------------------------------
| Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
--------------------------------------------------------------------------
|   0 | SELECT STATEMENT  |      |       |       |     3 (100)|          |
|*  1 |  TABLE ACCESS FULL| EMP  |     1 |    38 |     3   (0)| 00:00:01 |
--------------------------------------------------------------------------

Predicate Information (identified by operation id):





var v_num number;
EXEC  :v_num:=dbms_spm.alter_sql_plan_baseline(sql_handle =>'SQL_9d6ca16cee695f92',  plan_name => 'SQL_PLAN_9uv51dmr6krwkd8a279cc',  attribute_name=> 'fixed',  attribute_value=>'YES');  
print v_num;





after !!!
col sql_text for a50 wrap
col enabled for a15
col  accepted for a15
col fixed for a15
col CREATED for a30
select CREATED,sql_handle, plan_name, sql_text, enabled, accepted, fixed from dba_sql_plan_baselines
where 1=1
and CREATED >sysdate - interval '1' hour;
 
CREATED                        SQL_HANDLE           PLAN_NAME                      SQL_TEXT                                           ENABLED         ACCEPTED        FIXED
------------------------------ -------------------- ------------------------------ -------------------------------------------------- --------------- --------------- ---------------
13-NOV-22 12.17.02.000000 PM   SQL_9d6ca16cee695f92 SQL_PLAN_9uv51dmr6krwkd8a279cc select * from emp where ENAME=:ENAME               YES             YES             YES






 SELECT s.sql_id,b.sql_handle, b.sql_text, b.plan_name, b.enabled , b.accepted, b.fixed  FROM   dba_sql_plan_baselines b, gv$sql s
 WHERE  s.sql_id='7j5bb53huv8v1'
 AND    s.exact_matching_signature = b.signature;

SQL_ID        SQL_HANDLE           SQL_TEXT                                           PLAN_NAME                      ENABLED         ACCEPTED        FIXED
------------- -------------------- -------------------------------------------------- ------------------------------ --------------- --------------- ---------------
7j5bb53huv8v1 SQL_9d6ca16cee695f92 select * from emp where ENAME=:ENAME               SQL_PLAN_9uv51dmr6krwkd8a279cc YES             YES             YES





Our sql_id and PLAN_HASH_VALUE

set linesize 300 pagesize 300
col sql_text for a50 wrap
col SQL_PLAN_BASELINE for a25
col EXACT_MATCHING_SIGNATURE for 99999999999999999999999
col PLAN_HASH_VALUE for 9999999999999999
select distinct sql_id, plan_hash_value, s.exact_matching_signature, b.enabled, b.accepted, b.fixed ,s.sql_text from gv$sql s,dba_sql_plan_baselines b
where 1=1
--and sql_text like  '%select * from emp where ENAME=:ENAME%'
and sql_id='7j5bb53huv8v1';


SELECT sql_handle, plan_name,ENABLED,ACCEPTED,FIXED,REPRODUCED,OPTIMIZER_COST,to_char(Created,'DD-MON-YY') Created
FROM dba_sql_plan_baselines   WHERE signature IN ( SELECT exact_matching_signature FROM v$sql WHERE sql_id='&SQL_ID')

define sql_id='7j5bb53huv8v1'
SELECT sql_handle, plan_name,ENABLED,ACCEPTED,FIXED,REPRODUCED,OPTIMIZER_COST,to_char(Created,'DD-MON-YY hh:mi') Created
FROM dba_sql_plan_baselines
WHERE signature IN (
SELECT exact_matching_signature FROM v$sql WHERE sql_id='&SQL_ID')




SQL_HANDLE           PLAN_NAME                      ENABLED         ACCEPTED        FIXED           REP OPTIMIZER_COST CREATED
-------------------- ------------------------------ --------------- --------------- --------------- --- -------------- ------------------------------
SQL_9d6ca16cee695f92 SQL_PLAN_9uv51dmr6krwkd8a279cc YES             YES             YES             YES              3 13-NOV-22 12:17


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


some command !!!!!!!!!


var n number
begin
:n:=dbms_spm.load_plans_from_cursor_cache(sql_id=>'7j5bb53huv8v1', plan_hash_value=>928732588, fixed =>'NO’, enabled=>'YES');
end;
/




var v_num number;
exec :v_num:=dbms_spm.alter_sql_plan_baseline(sql_handle =>'SQL_handle_value',  plan_name => 'plan_name_value',  attribute_name=> 'enabled',  attribute_value=>'YES'); 
print v_num;

var v_num number;
EXEC  :v_num:=dbms_spm.alter_sql_plan_baseline(sql_handle =>'SQL_handle_value',  plan_name => 'plan_name_value',  attribute_name=> 'fixed',  attribute_value=>'YES');  
print v_num;


Disable the SQL Plan in SQL plan Baseline in Oracle

var v_num number;
exec :v_num:=dbms_spm.alter_sql_plan_baseline(sql_handle =>'SQL_handle_value',  plan_name => 'plan_name_value',  attribute_name=> 'enabled',  attribute_value=>'NO'); 
print v_num;

var v_num number;
EXEC  :v_num:=dbms_spm.alter_sql_plan_baseline(sql_handle =>'SQL_handle_value',  plan_name => 'plan_name_value',  attribute_name=> 'fixed',  attribute_value=>'NO');  
print v_num;




ww

set serveroutput on
set line 999 pages 999
select dbms_spm.evolve_sql_plan_baseline(sql_handle => 'SYS_SQL_1046c141c5de11a8',plan_name => 'sql_plan_10jq1872xw4d8c079fdff') from dual;




SET SERVEROUTPUT ON  LONG 10000
DECLARE
x clob;
BEGIN
x := dbms_spm.evolve_sql_plan_baseline('SQL_9d6ca16cee695f92','SQL_PLAN_9uv51dmr6krwkd8a279cc',
VERIFY=>'YES',
COMMIT=>'YES');
DBMS_OUTPUT.PUT_LINE(x);
END;
/


set serveroutput on
declare
v_sql_plan_id  pls_integer;
begin
v_sql_plan_id := dbms_spm.alter_sql_plan_baseline(
sql_handle      => 'sys_sql_1046c141c5de11a8',
plan_name       => 'sql_plan_10jq1872xw4d8cf314e9e',
attribute_name  => 'fixed',
attribute_value => 'YES');
end;
/

to check sql ...


from   http://anuj-singh.blogspot.com/2021/02/      SQL Report ....   / SQL info ... 

var sqlid varchar2(30)
 begin :sqlid := '7j5bb53huv8v1'; end;  ---- sql id here!!!!
/

set long 50000 pagesize 500 linesize 300
col frm         heading from 
select * from (select 'gv$sql' frm ,  sql_fulltext from gv$sql where sql_id=:sqlid
               union all
               select 'dba_hist', sql_text from dba_hist_sqltext where sql_id=:sqlid 
	   );



define sql_id='7jycxu86n60qh'

col plan_table_output for a150
select plan_table_output
from table(dbms_xplan.display_cursor('&sql_id', null, 'BASIC'))
union all
select * from table(dbms_xplan.display_awr('&sql_id', null, null, 'ALL'))



-- Purge the Shared Pool 

select 'exec sys.dbms_shared_pool.purge('''||address||', '||hash_value||''', ''c'')'
from gv$sql
where sql_id = :sqlid
--and child_number=&childnr
;


set linesize 300
col begin_interval_time for a28
select ss.snap_id, ss.instance_number node, begin_interval_time, sql_id, plan_hash_value, nvl(executions_delta,0) execs,
(elapsed_time_delta/decode(nvl(executions_delta,0),0,1,executions_delta))/1000000 	avg_etime,
(buffer_gets_delta/decode(nvl(buffer_gets_delta,0),0,1,executions_delta)) 		avg_lio,
(disk_reads_delta/decode(nvl(disk_reads_delta,0),0,1,executions_delta)) 		avg_pio,
(rows_processed_delta/decode(nvl(rows_processed_delta,0),0,1,executions_delta)) 	avg_rows,
(CPU_TIME_DELTA/decode(nvl(CPU_TIME_DELTA,0),0,1,executions_delta))/1000000 		avg_cpu_wait,
(IOWAIT_DELTA/decode(nvl(IOWAIT_DELTA,0),0,1,executions_delta))/1000000 		avg_user_io_wait,
(CLWAIT_DELTA/decode(nvl(CLWAIT_DELTA,0),0,1,executions_delta))/1000000 		avg_clu_wait,
(APWAIT_DELTA/decode(nvl(APWAIT_DELTA,0),0,1,executions_delta))/1000000 		avg_app_wait,
(CCWAIT_DELTA/decode(nvl(CCWAIT_DELTA,0),0,1,executions_delta))/1000000 		avg_concurrent_wait
from DBA_HIST_SQLSTAT S, DBA_HIST_SNAPSHOT SS
where sql_id = :sql_id --sql_id 
and ss.snap_id = S.snap_id 
and ss.instance_number = S.instance_number 
and executions_delta > 0 order by 1, 2, 3


define sql_id='7jycxu86n60qh'

set lines 1000 pages 9999
col instance_number FOR 9999    HEA 'Inst'
col end_time 			HEA 'End Time'
col plan_hash_value 	        HEA 'Plan|Hash Value'

col rows_per_exec 		HEA 'Rows Per Exec'
col et_secs_per_exec 	HEA 'Elap Secs|Per Exec'
col cpu_secs_per_exec 	HEA 'CPU Secs|Per Exec'
col io_secs_per_exec 	HEA 'IO Secs|Per Exec'
col cl_secs_per_exec 	HEA 'Clus Secs|Per Exec'
col ap_secs_per_exec 	HEA 'App Secs|Per Exec'
col cc_secs_per_exec 	HEA 'Conc Secs|Per Exec'
col pl_secs_per_exec 	HEA 'PLSQL Secs|Per Exec'
col ja_secs_per_exec 	HEA 'Java Secs|Per Exec'
col executions_total   FOR 999,999 HEA 'Execs|Total'
select 'gv$dba_hist_sqlstat' source,h.instance_number,
to_char(CAST(s.begin_interval_time AS DATE), 'DD-MM-YYYY HH24:MI') snap_time,
to_char(CAST(s.end_interval_time AS DATE), 'DD-MM-YYYY HH24:MI') end_time,
h.sql_id,
h.plan_hash_value,
h.executions_total,
to_char(ROUND(h.rows_processed_total / h.executions_total), '999,999,999,999') 		rows_per_exec,
to_char(ROUND(h.elapsed_time_total / h.executions_total / 1e6, 3), '999,990.000') 	et_secs_per_exec,
to_char(ROUND(h.cpu_time_total / h.executions_total / 1e6, 3), '999,990.000') 		cpu_secs_per_exec,
to_char(ROUND(h.iowait_total / h.executions_total / 1e6, 3), '999,990.000') 		io_secs_per_exec,
to_char(ROUND(h.clwait_total / h.executions_total / 1e6, 3), '999,990.000') 		cl_secs_per_exec,
to_char(ROUND(h.apwait_total / h.executions_total / 1e6, 3), '999,990.000') 		ap_secs_per_exec,
to_char(ROUND(h.ccwait_total / h.executions_total / 1e6, 3), '999,990.000') 		cc_secs_per_exec,
to_char(ROUND(h.plsexec_time_total / h.executions_total / 1e6, 3), '999,990.000') 	pl_secs_per_exec,
to_char(ROUND(h.javexec_time_total / h.executions_total / 1e6, 3), '999,990.000') 	ja_secs_per_exec
FROM dba_hist_sqlstat h,dba_hist_snapshot s
WHERE h.sql_id = '&sql_id'
AND h.executions_total > 0
AND s.snap_id = h.snap_id
AND s.dbid = h.dbid
AND s.instance_number = h.instance_number
UNION ALL
SELECT 'gv$sqlarea_plan_hash' source,h.inst_id,
TO_CHAR(sysdate, 'DD-MM-YYYY HH24:MI') snap_time,
TO_CHAR(sysdate, 'DD-MM-YYYY HH24:MI') end_time,
h.sql_id,
h.plan_hash_value,
h.executions,
to_char(ROUND(h.rows_processed / h.executions), '999,999,999,999') 				rows_per_exec,
to_char(ROUND(h.elapsed_time / h.executions / 1e6, 3), '999,990.000') 				et_secs_per_exec,
to_char(ROUND(h.cpu_time / h.executions / 1e6, 3), '999,990.000') 				cpu_secs_per_exec,
to_char(ROUND(h.USER_IO_WAIT_TIME / h.executions / 1e6, 3), '999,990.000') 			io_secs_per_exec,
to_char(ROUND(h.CLUSTER_WAIT_TIME / h.executions / 1e6, 3), '999,990.000') 			cl_secs_per_exec,
to_char(ROUND(h.APPLICATION_WAIT_TIME / h.executions / 1e6, 3), '999,990.000') 			ap_secs_per_exec,
to_char(ROUND(h.CLUSTER_WAIT_TIME / h.executions / 1e6, 3), '999,990.000') 			cc_secs_per_exec,
to_char(ROUND(h.PLSQL_EXEC_TIME / h.executions / 1e6, 3), '999,990.000') 			pl_secs_per_exec,
to_char(ROUND(h.JAVA_EXEC_TIME / h.executions / 1e6, 3), '999,990.000') 			ja_secs_per_exec
FROM gv$sqlarea_plan_hash h
WHERE h.sql_id = '&sql_id'
--and h.inst_id=inst_id
AND h.executions > 0
order by source ;



col inst 		for 99999999
col sid 		for 9990
col serial# 		for 999990
col username 		for a12
col osuser 		for a16
col program 		for a10 trunc
col Locked 		for a6
col status 		for a1 trunc print
col "hh:mm:ss" 		for a8
col SQL_ID 		for a15
col seq# 								for 99990
col event heading 'Current/LastEvent' 	for a25 trunc
col state head 'State (sec)' 			for a14
 col kill 								for a15
select ''''||sid ||','|| serial#||',@'||inst_id ||'''' kill, username, 
ltrim(substr(osuser, greatest(instr(osuser, '\', -1, 1)+1,length(osuser)-14))) osuser,
substr(program,instr(program,'/',-1)+1,
decode(instr(program,'@'),0,decode(instr(program,'.'),0,length(program),instr(program,'.')-1),instr(program,'@')-1)) program,  decode(lockwait,NULL,' ','L') locked, status, 
to_char(to_date(mod(last_call_et,86400), 'sssss'), 'hh24:mi:ss') "hh:mm:ss",
SQL_ID, seq# , event, 
decode(state,'WAITING','WAITING '||lpad(to_char(mod(SECONDS_IN_WAIT,86400),'99990'),6),'WAITED SHORT TIME','ON CPU','WAITED KNOWN TIME','ON CPU',state) state,substr(module,1,25) module, substr(action,1,20) action
from GV$SESSION 
where type = 'USER'
and audsid != 0    -- to exclude internal processess
and sql_id= :sqlid
order by inst_id, status, last_call_et desc, sid
/

Oracle DBA

anuj blog Archive