Archive

Archive for the ‘How To’ Category

ERROR: ORA-00257: archiver error. Connect internal only, until freed.

Cause: The archiver process received an error while trying to archive a redo log. If the problem is not resolved soon, the database will stop executing transactions. The most likely cause of this message is the destination device is out of space to store the redo log file.

Action: Check archiver trace file for a detailed description of the problem. Also verify that the device specified in the initialization parameter ARCHIVE_LOG_DEST is set up properly for archiving.alter database flashback on

There is two possible way to solution.
1. without increasing DB_RECOVERY_FILE_DEST_SIZE.
2. by increasing DB_RECOVERY_FILE_DEST_SIZE.

Without increasing DB_RECOVERY_FILE_DEST_SIZE.
1. Check whether the database is in archive log mode and automatic archiving is enabled.

 SQL> archive log list;
 Database log mode              Archive Mode
 Automatic archival             Enabled
 Archive destination            USE_DB_RECOVERY_FILE_DEST
 Oldest online log sequence     29
 Next log sequence to archive   31
 Current log sequence           31

2. If archive destination is defined by USE_DB_RECOVERY_FILE_DEST, find the archive destination by:

SQL> show parameter db_recovery_file_dest;
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
db_recovery_file_dest                string      C:\oracle\product\10.2.0/flash_recovery_area
db_recovery_file_dest_size           big integer 2G

Check what the value for db_recovery_file_dest_size.

3. Find the space used in flash recovery area by using following SQL:

col ROUND(SPACE_LIMIT/1048576) heading “Space Allocated (MB)” format 999999
col round(space_used/1048576) heading “Space Used (MB)” format 99999
col name format a40
select name, round(space_limit/1048576) As space_limit,round(space_used/1048576) As space_used
from v$RECOVERY_FILE_DEST;

4. if SPACE_USED is equal to SPACE_LIMIT of db_recovery_file_dest, move the archive logs to different destination.

5. Archive all the log files

SQL> alter system archive log all;

6. Just switch the logs to verify

 SQL> alter system switch logfile;

7. DB_RECOVERY_FILE_DEST_SIZE is to delete (archive log) files from DB_RECOVERY_FILE_DEST if you are sure you have backups and the archived logs are no longer necessary.

 
 $rman target /
 RMAN>delete archivelog until time 'SYSDATE-1';
 or,
 RMAN>delete archivelog all;

By increasing DB_RECOVERY_FILE_DEST_SIZE.
1. See the path of flash recovery area.

 SQL> show parameter db_recovery_file_dest;

2. Increase the Flash Recovery Area

SQL> ALTER SYSTEM SET db_recovery_file_dest_size='10G' SCOPE=BOTH;
Sytem Altered.

CreateFile error 32 when trying set file time

March 24, 2011 Leave a comment

Today I am going to install Oracle 10g Client and ODAC11gR2 (Oracle Data Provider .Net) in Microsoft Windows XP Professional Service Pack 2. I have got following error message in console.

CreateFile error 32 when trying set file time

After searching I have found that this error message for my Antivirus. In my case the anti virus is Kaspersky. After disable my antivirus I am able to install Oracle Client with out any Warning or Error message

ORA-00439: feature not enabled: Flashback Database

March 13, 2011 Leave a comment

Some feature is not enabled in oracle database standard edition, as a result we can not use flashback feature in Oracle Database if you are use in standard edition of oracle.

Following Error Message show in Oracle 10g standard edition

SQL> alter database flashback on;
alter database flashback on
*
ERROR at line 1:
ORA-00439: feature not enabled: Flashback Database

Version of Oracle

SQL> SELECT * FROM V$VERSION;
BANNER
----------------------------------------------------------------
Oracle Database 10g Release 10.2.0.1.0 - Production
PL/SQL Release 10.2.0.1.0 - Production
CORE    10.2.0.1.0      Production
TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
NLSRTL Version 10.2.0.1.0 - Production

Features are available in standard edition

SQL> SELECT Parameter,Value FROM V$OPTION Where Value = 'TRUE';
PARAMETER                                                        VALUE                                                           
----------------------------------------------------------------------
Objects                                                          TRUE                                                            
Connection multiplexing                                          TRUE                                                            
Connection pooling                                               TRUE                                                            
Database queuing                                                 TRUE                                                            
Incremental backup and recovery                                  TRUE                                                            
Instead-of triggers                                              TRUE                                                            
Parallel load                                                    TRUE                                                            
Proxy authentication/authorization                               TRUE                                                            
Plan Stability                                                   TRUE                                                            
Transparent Application Failover                                 TRUE                                                            
Sample Scan                                                      TRUE                                                            
Java                                                             TRUE                                                            
OLAP Window Functions                                            TRUE

So flashback database is disabled in standard edition or in standard one  edition. To be able to flashback on you have to use enterprise edition.

ORA-01775: looping chain of synonyms

March 12, 2011 Leave a comment
Cause: Through a series of CREATE synonym statements, a synonym was defined that referred to itself.
Action: Change one synonym definition so that it applies to a base table or view and retry the operation.

For example, the following definitions are circular: CREATE SYNONYM s1 for s2;
CREATE SYNONYM s2 for s3
CREATE SYNONYM s3 for s1
or
CREATE SYNONYM s4 for s4

Check your synonyms with:
select * from all_synonyms where synonym_name = ‘name’ or table_name = ‘name’;

SELECT table_owner, table_name, db_link
FROM dba_synonyms
WHERE owner = 'PUBLIC'
AND synonym_name = <<synonym name>>

select owner, synonym_name, connect_by_iscycle CYCLE
from dba_synonyms
where connect_by_iscycle > 0
connect by nocycle prior table_name = synonym_name
and prior table_owner = owner
union
select 'PUBLIC', synonym_name, 1
from dba_synonyms
where owner = 'PUBLIC'
and table_name = synonym_name
and (table_name, table_owner) not in (select object_name, owner from dba_objects
where object_type != 'SYNONYM')

Shared Memory Realm does not exist

December 20, 2010 Leave a comment

ERROR:

ORA-01034: ORACLE not available

ORA-27101: shared memory realm does not exist

Solution :

check ORACLE_SID has value if not exist then set ORACLE_SID

For Windows Environment

set ORACLE_SID=orcl 
echo %ORACLE_SID% 
orcl 

For Linux Environment

$ export ORACLE_SID=orcl

Now You need to Manually startup the database

sqlplus "sys/password as sysdba" 
Connected to an idle instance.
SQL> startup;
ORACLE instance started.
Total System Global Area  574619648 bytes
Fixed Size                  1250236 bytes
Variable Size             192941124 bytes
Database Buffers          377487360 bytes
Redo Buffers                2940928 bytes
Database mounted.
Database opened.
SQL> exit

Basic Concept of Performance Tuning in Oracle

October 25, 2010 Leave a comment

Scope of Performance Tuning

There is four main area for Performance Tuning.

1. SQL Tuning          – Responsibility of the Developer
2. Database Tuning     – Responsibility of the Database Administrator
3. System Tuning       – Responsibility of the System Administrator
4. Network Tuning      – Responsibility of the Network / LAN / WAN Administrator.

SQL Tuning

1. Find the problem to a single SQL

You may be lucky and know already the exact SQL causing the problem. If so, move straight on to the second step. Otherwise, click on the link above for help on finding the problem SQL.

2. Analyze the SQL to determine the nature of the problem

Most performance problems are quite common and easy to fix. This section will describe some of these and how to spot them, and then go on to describe a more general analysis method.

3. Fix the problem.

Almost every performance problem has a solution; it’s just that some are more complex than others. In order of increasing complexity and expense, such fixes include:
  • Analyze the underlying table to give Oracle’s Cost Based Optimizer the information it needs to resolve the SQL efficiently.
  • Add one or more hints to the SQL to encourage or discourage certain execution plans.
  • Minor changes to the SQL to encourage or discourage certain execution plans.
  • Restructure a poorly designed SQL that cannot be resolved efficiently.
  • Alter the underlying infrastructure. eg. Add or change (or even remove!) indexes; introduce clusters, partitions or index-organised tables; denormalize tables; use materialized views. Note that these actions venture outside the scope of this document, and should only be performed with the prior permission of (and preferably assistance from) the DBA and/or System Architect.
  • Refer the problem to the database administrator. Possible solutions here would include tuning the Oracle instance, restructuring or moving tablespaces, or archiving old data.
  • Refer the problem to the System Adminstrator. Possible solutions may include reconfiguration of existing hardware, or acquisition of new hardware.

Database Tuning

For optimum performance an Oracle database should be regularly tuned. Only tune a database after it has been up and running for a little while.
  • Tuning the cache hit ratio
  • Tuning the library cache
  • Tuning the log buffer
  • Tuning buffer cache hit ratio
  • Tuning sorts
  • Tuning rollback segments
  • Identifying missing indexes
  • Identifying index fragmentation
  • Identifying free list contention
  • Identify significant reparsing of SQL
  • Reducing database fragmentation
  • Rebuilding indexes
  • Reduce thrashing or poor system performance (or how to un-tune oracle?!)

System Tuning(Operating System)

Tune your operating system according to your operating system documentation. For Windows platforms, the default settings are usually sufficient. However, the Solaris and Linux platforms usually need to be tuned appropriately. The following sections describe issues related to operating system performance:
  • Basic OS Tuning Concepts
  • Solaris Tuning Parameters
  • Linux Tuning Parameters
  • HP-UX Tuning Parameters
  • Windows Tuning Parameters
  • Other Operating System Tuning Information
Details

Network Tuning

Network tuning is the performance optimization and tuning of SQL*Net based on an arbitrary UNP which could be TCP/IP, SPX/IP or DECnet. SQL*Net performance can be maximized by synchronization with tunable parameters of the UNP, for example, buffer size.SQL*Net transaction performance can be divided into components of connect time and query time, where
Total SQL*Net (Net8) Transaction Time = Connect Time + Query Time 

Connect time can be maximized by calibration of tunable parameters of SQL*Net and the UNP when designing and implementing networks.

SQL*Net Performance
For this discussion, SQL*Net performance and tuning analysis is based on two categories:

  • SQL*Net performance
  • SQL*Net tuning
Details1 

Details2


DB_WRITER_PROCESSES

September 20, 2010 Leave a comment

Setting the DB_WRITER_PROCESSES parameter (Background process DBWR) to a value greater than one is supported starting with the Oracle 8.0 release.

Multiple DBWR processes are mainly used to simulate asynchronous I/O when the operating system does not support it.  Since Windows NT and Windows 2000 use asynchronous I/O by default, using multiple DBWR processes may not necessarily improve performance.  Increasing this parameter is also likely to have minimal effect on single-CPU systems.  Increasing this parameter could, in fact, reduce performance on systems where the CPU’s are already over burdened.  In cases where the main performance bottleneck is that a single DBWR process cannot keep up with the work load, then increasing the value for DB_WRITER_PROCESSES may improve performance.

When increasing DB_WRITER_PROCESSES it may also be necessary to increase the DB_BLOCK_LRU_LATCHES parameter, as each DBWR process requires an LRU latch.

How to change db_writer_processes parameter

SQL> show parameter db_writer_processes
NAME                                 TYPE        VALUE
------------------------------------ ----------- -------
db_writer_processes                  integer     1

SQL> alter system set db_writer_processes=2 scope=spfile sid='*';

System altered.

Now restart the database to take the change effect.

 
SQL> show parameter db_writer_processes

NAME                                 TYPE        VALUE
------------------------------------ ----------- -------
db_writer_processes                  integer     2

“The number of DBWR should be two times the number of CPUs (vary 1 or 2 depending on idle state of CPUs during production/test run)”

DB_WRITER_PROCESSES = 2 * number of CPU

Default value of DB_WRITER_PROCESSES is 1 or CPU_COUNT / 8, whichever is greater. If the number of processor groups is less than 36 but greater than the number of DB writer processes, then the number of DB writer processes is adjusted to be a multiple of the number of processor groups. If the number of DB writer processes is greater than or equal to the number of processor groups, then there is no adjustment.

Range of value in Oracle 10g- 1 to 20 but in Oracle 11g – 1 to 36.

Convert Number to Word

September 6, 2010 Leave a comment
SQL> select to_char(to_date(5358452,'J'),'JSP') from dual;
TO_CHAR(TO_DATE(5358452,'J'),'JSP')
----------------------------------------------------------------------
FIVE MILLION THREE HUNDRED FIFTY-EIGHT THOUSAND FOUR HUNDRED FIFTY-TWO

Restriction: It can conversion from 1 to 5373484 and it can not conversion decimal number.

A function for convert number to word

create or replace
function spell_number( p_number in number )
   return varchar2
   as
       type myArray is table of varchar2(255);
       l_str    myArray := myArray( '',
                              ' thousand '    , ' million ',
                              ' billion '     , ' trillion ',
                              ' quadrillion ' , ' quintillion ',
                              ' dont read '   , ' septillion ',
                              ' octillion '   , ' nonillion ',
                              ' decillion '   , ' undecillion ',
                              ' duodecillion ');

       l_num   varchar2(50) default trunc( p_number );
       l_return varchar2(4000);
   begin
       for i in 1 .. l_str.count
       loop
          exit when l_num is null;

           if ( substr(l_num, length(l_num)-2, 3) <> 0 )
           then
              l_return := to_char(
                              to_date(
                               substr(l_num, length(l_num)-2, 3),
                                 'J' ),
                          'Jsp' ) || l_str(i) || l_return;
           end if;
           l_num := substr( l_num, 1, length(l_num)-3 );
       end loop;

       return l_return;
   end;
 /

Example

SQL> Select spell_number( 1234567899 ) From dual;

SPELL_NUMBER(1234567899)
------------------------
One billion Two Hundred Thirty-Four million 
Five Hundred Sixty-Seven thousand Eight Hundred 
Ninety-Nine

ORA-19809: limit exceeded for recovery files

June 28, 2010 Leave a comment
C:\Documents and Settings\Administrator>sqlplus "/as sysdba"

SQL*Plus: Release 10.2.0.1.0 - Production on Mon Jun 28 10:25:39 2010
Copyright (c) 1982, 2005, Oracle.  All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> select * from tab;
select * from tab
              *
ERROR at line 1:
ORA-01219: database not open: queries allowed on fixed tables/views only
 

Shutdown the database first

SQL> shutdown immediate;
ORA-01109: database not open
Database dismounted.
ORACLE instance shut down.

Start the database

SQL> startup
ORACLE instance started.

Total System Global Area  599785472 bytes
Fixed Size                  1250356 bytes
Variable Size             180358092 bytes
Database Buffers          411041792 bytes
Redo Buffers                7135232 bytes
Database mounted.
ORA-16038: log 2 sequence# 135 cannot be archived
ORA-19809: limit exceeded for recovery files
ORA-00312: online log 2 thread 1:
'F:\ORACLE\PRODUCT\10.2.0\ORADATA\ORCL\REDO02.LOG'

Problem: The value db_recovery_file_dest_size is not enough for generate archive log

          
SQL> show parameter DB_RECOVERY_FILE_DEST_SIZE;

NAME                                 TYPE        VALUE
------------------------------------ ----------- -------------------
db_recovery_file_dest_size           big integer 2G

Solution: Increase the value of db_recovery_file_dest_size following way.

 
SQL> ALTER SYSTEM SET DB_RECOVERY_FILE_DEST_SIZE = 10G;

System altered.

Now open the database.

SQL> alter database open;

Database altered.

Cancel-Based Recovery

June 22, 2010 Leave a comment

A cancel-based recovery is a type of user-managed incomplete recovery that is performed by specifying the UNTIL CANCEL clause with the RECOVER command (a SQL*Plus command that is used to recover a database). The UNTIL CANCEL clause specifies that the recovery process will continue until the user manually cancels the recovery process issuing the CANCEL command.

In a cancel-based incomplete recovery, the recovery process proceeds by prompting the user with the suggested archived redo log files’ names. The recovery process stops when the user specifies CANCEL instead of specifying an archived redo log file’s name. If the user does not specify CANCEL, the recovery process automatically stops when all the archived redo log files have been applied to the database.

A cancel-based recovery is usually performed when the requirement is to recover up to a particular archived redo log file. For example, if one of the archived redo log files required for the complete recovery is corrupt or missing, the only option is to recover up to the missing archived redo log file.

Recovery Scenario Preferred Recovery Method
Some important table is dropped Oracle Time-based Recovery based Recovery
Some bad data is committed in a table Oracle Time-based Recovery based Recovery
Lost archive log results in failure of  complete recovery Oracle Cancel-based Recovery
Backup control file does not know anything about the arhivelogs Oracle Cancel-based Recovery
All unarchived Redo Logs and datafiles are lost Oracle Cancel-based Recovery
Recovery is needed up to a specific archived log file Oracle Cancel-based Recovery
Recovery through Resetlogs when media failure occurs before backup completion. Oracle Change-based Recovery
A Tablespace is dropped Recovery with a backup control file

1. Start SQL*Plus and connect to Oracle with administrator privileges. For example, enter:

sqlplus '/ AS SYSDBA'

2. Start a new instance and mount the database:

STARTUP MOUNT

3. Begin cancel-based recovery by issuing the following command:

RECOVER DATABASE UNTIL CANCEL

If you are using a backup control file with this incomplete recovery, then specify the USING BACKUP CONTROLFILE option in the RECOVER command.

RECOVER DATABASE UNTIL CANCEL USING BACKUP CONTROLFILE

4. Oracle applies the necessary redo log files to reconstruct the restored datafiles. Oracle supplies the name it expects to find from LOG_ARCHIVE_DEST_1 and requests you to stop or proceed with applying the log file. Note that if the control file is a backup, then you must supply the names of the online logs if you want to apply the changes in these logs.

5. Continue applying redo log files until the last log has been applied to the restored datafiles, then cancel recovery by executing the following command:

CANCEL

Oracle returns a message indicating whether recovery is successful. Note that if you cancel recovery before all the datafiles have been recovered to a consistent SCN and then try to open the database, you will get an ORA-1113 error if more recovery is necessary for the file. You can query V$RECOVER_FILE to determine whether more recovery is needed, or if a backup of a datafile was not restored prior to starting incomplete recovery.

6. Open the database in RESETLOGS mode. You must always reset the online logs after incomplete recovery or recovery with a backup control file. For example, enter:

ALTER DATABASE OPEN RESETLOGS;

For More Detail please visit here

How to Clear Buffer Cash and Shared Pool in Oracle 10g

Flush buffer cache to clear recently cached data blocks

SQL> alter system flush buffer_cache;
System altered.

Flush shared pool to clear recently created SQL parse and execution plan

SQL> alter system flush shared_pool;
System altered.

What is the Difference between “clear buffer” and “alter system flush buffer_cache

Clear Buffer SQL* Plus Command which is use to clear the SQL*Plus screen and the screen buffer.

Syntax:
CLEAR {BREAKS|BUFFER|COLUMNS|COMPUTES|SCREEN|SQL TIMING}
SQL> clear buffer
buffer cleared
Example:
SQL> Select empno, ename from Scott.emp Where ename='KING';
     EMPNO ENAME
---------- ----------
      7839 KING
SQL> list;
  1* Select empno, ename from Scott.emp Where ename='KING'
SQL> clear buffer;
buffer cleared
SQL> list
SP2-0223: No lines in SQL buffer.

But alter system flush buffer_cache use to clear data buffer cash in SGA.

How delete duplicate rows from a Table

Creating Table and Insert some sample Data

CREATE TABLE PROC_DATA_LOG
  (
    CN      VARCHAR2(20 BYTE),
    A_DATA  VARCHAR2(400 BYTE)
  );
Select * from PROC_DATA_LOG;

CN                   A_DATA                                          
-------------------- ------------
1                    Test Data 1
1                    Test Data 1
2                    Test Data 2
3                    Test Data 3
3                    Test Data 3
4                    Test Data 4
5                    Test Data 5

SQL to delete the duplicate rows

DELETE FROM PROC_DATA_LOG  
WHERE ROWID NOT IN (
                    SELECT MAX (ROWID)
                    FROM PROC_DATA_LOG
                    GROUP BY CN
                   );

All duplicate row base on CN is deleted

Select * from PROC_DATA_LOG;

CN                   A_DATA                                                   
-------------------- ------------
1                    Test Data 1
2                    Test Data 2
3                    Test Data 3
4                    Test Data 4
5                    Test Data 5

Delete Duplicate Rows using Analytic functions

DELETE FROM PROC_DATA_LOG
WHERE ROWID IN ( 
        SELECT ROWID
        FROM (
              SELECT
              ROW_NUMBER() OVER (PARTITION BY CN ORDER BY CN) rnk
              FROM   PROC_DATA_LOG
             )
        WHERE rnk>1
        );

Customize SPLIT Function written in Oracle (PLSQL)

February 23, 2010 Leave a comment

A common task when selecting data from a database is to take a set of values a query returns and format it as a comma delimited list. Another task that’s almost as common is the need to do the reverse take a comma delimited list of values in a single string and use it as a table of values.

To serve this purpose I preferred following function to Split string.

Split Function:

create or replace function split(
  p_InputString   varchar2,
  p_Position      number,
  p_Delimiter     varchar2
  )
return varchar2
is
   v_list varchar2(32767) := p_Delimiter || p_InputString;
   v_start_position number;
   v_end_position number;
begin
   v_start_position := instr(v_list, p_Delimiter, 1, p_Position);
   if v_start_position > 0 then
      v_end_position := instr( v_list, p_Delimiter, 1, p_Position + 1);
         if v_end_position = 0 then
            v_end_position := length(v_list) + 1;
         end if;
         return(substr(v_list, v_start_position + 1, v_end_position - v_start_position - 1));
   else
         return NULL;
   end if;
end split;
/
Show Error

Output 1:

select split('Tamim Khan',1,' ') from dual;
SPLIT('TAMIMKHAN',1,'')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
-----------------------------------------
Tamim

Output 2:

select split('Tamim Khan',2,' ') from dual;

SPLIT('TAMIMKHAN',1,'')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
------------------------------------------
Khan

Output 3:

select split('Dhanmondi,Dhaka',1,',') from dual;                        
SPLIT('TAMIMKHAN',1,'')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
----------------------------------------------
Dhanmondi

Output 4:

select split('Dhanmondi,Dhaka',2,',') from dual;                        
SPLIT('TAMIMKHAN',1,'')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
----------------------------------------------
Dhaka
Categories: SPLIT Function Tags: ,

Wrapping PL/SQL

February 18, 2010 Leave a comment

Wrapping PL/SQL source is not so different using this method than it is using the WRAP binary. It is more flexible. Oracle developers can take advantage of many PL/SQL or Java utilities that exist in $ORACLE_HOME/bin or in supplied packages.

These utilities can load, encrypt, tune or debug code objects.  This chapter will focus on the utilities that perform these functions, including wrap, dbms_profiler, dbms_debug, loadjava, dropjava and loadpsp.

The first of these utilities to be discussed will be the wrap utility that allows PL/SQL developers to encrypt their code.

Procedure/Function                Description

WRAP                                     Overloaded function that returns the wrapped PL/SQL source code when provided with the original source.

CREATE_WRAPPED             Procedure that wraps the source code provided as input. It’s faster than using WRAP.

Create Country Table

SQL Code:
CREATE TABLE COUNTRIES
  (
    C_NAME  VARCHAR2(15 BYTE)
  );

Insert Data into Country Table

SQL Code:
REM INSERTING into COUNTRIES
Insert into COUNTRIES (C_NAME) values ('Poland');
Insert into COUNTRIES (C_NAME) values ('Germany');
Insert into COUNTRIES (C_NAME) values ('United States');
Insert into COUNTRIES (C_NAME) values ('Portugal');
Insert into COUNTRIES (C_NAME) values ('Czech Republic');
Insert into COUNTRIES (C_NAME) values ('China');
Insert into COUNTRIES (C_NAME) values ('Slovakia');
Insert into COUNTRIES (C_NAME) values ('Slovenia');

The DBMS_DDL package for Dynamic Wrapping

Use the overloaded WRAP function with EXECUTE IMMEDIATE to create the wrapped code, as the following example illustrates:

SQL Code:
DECLARE
  v_Procedure VARCHAR2(32767);
BEGIN
  v_Procedure :=  'create or replace PROCEDURE p_CountryList '
                  || 'AS '
                  || 'cursor crCountryList is '
                  || 'SELECT C_NAME FROM COUNTRIES; '
                  || 'BEGIN '
                  || ' for rc_countryList in crCountryList loop '
                  || '    dbms_output.put_line(rc_countryList.C_NAME);'
                  || ' end loop; '
                  || ' End;'; 
  EXECUTE IMMEDIATE DBMS_DDL.WRAP(v_Procedure);
END;

To see the wrapped procedure, select the text from the USER_SOURCE view.

SQL Code:
SELECT text
FROM user_source WHERE name = 'P_COUNTRYLIST';
 
Output:
TEXT                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
---------------------------------------------------------------------------
PROCEDURE p_CountryList wrapped                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
a000000                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
b2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
abcd                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
7                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
c2 d2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
OBXTyU790UHZX1Pz/x6SK6zaQdowg0zwLcsVfC+EOo7QS9JbZQ2c1RiJi1GYkXCXR+Hnl92a                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
6yUmVMJdr3L/xdu8xYazffm813KuNLzJ0jnlJ1HKbCYmfWw51ec5hoXDZ2KBtgvDWEsq4RNq                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
3cHIqVKojYPLLqq6zBQLjSwb9gkM4mO6aOBaz2jrVZ+/wI9dqhpqq1XumZC83+s=

Execute the wrapped procedure to verify all works as expected

Set Serveroutput on
execute p_CountryList;

This returns the following result

Poland
Germany
United States
Portugal
Czech Republic
China
Slovakia
Slovenia

CREATE_WRAPPED

DBMS_DDL.CREATE_WRAPPED works in a similar way. The use of EXECUTE IMMEDIATE is not required.

Use SYS.DBMS_DDL.CREATE_WRAPPED (v_procedure)
with replace of EXECUTE IMMEDIATE DBMS_DDL.WRAP(v_Procedure)

PL/SQL Wrap Utility for Encryption

The wrap utility (wrap.exe) provides a way for PL/SQL developers to protect their intellectual property by making their PL/SQL code unreadable.

Instead, the wrap utility takes a readable, ASCII text file as input and converts it to a file containing byte code.  The result is that the DBA, developers or anyone with database access cannot view the source code in any readable format.

The command line options for wrap are:

wrap iname=[file] oname=[file]

· iname – The name of the unencrypted PL/SQL file to be used as input (your source file).

· oname – The name of the output file.  This file will be encrypted.

For more information http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96624/c_wrap.htm

Categories: Wrapping PL/SQL Tags:

How to use Ref Cursor example

February 17, 2010 Leave a comment

How to use Ref Cursor example

REF CURSOR is basically a data type.  A variable created based on such a data type is generally called a cursor variable.  A cursor variable can be associated with different queries at run-time.  The primary advantage of using cursor variables is their capability to pass result sets between sub programs (like stored procedures, functions, packages etc.).

Declaring a SYS_REFCURSOR Cursor Variable

The following is the syntax for declaring a SYS_REFCURSOR cursor variable:

name SYS_REFCURSOR;

name is an identifier assigned to the cursor variable.

The following is an example of a SYS_REFCURSOR variable declaration.

DECLARE
    rc_emp SYS_REFCURSOR;

Opening a Cursor Variable

Once a cursor variable is declared, it must be opened with an associated SELECT command. The OPEN FOR statement specifies the SELECT command to be used to create the result set.

Syntax:
OPEN name FOR query;

name is the identifier of a previously declared cursor variable.  Query is a SELECT command that determines the result set when the statement is executed. The value of the cursor variable after the OPEN FOR statement is executed identifies the result set.

Declaring a User Defined REF CURSOR Type Variable

You must perform two distinct declaration steps in order to use a user defined REF CURSOR variable:

  • Create a referenced cursor TYPE
  • Declare the actual cursor variable based on that TYPE

The syntax for creating a user defined REF CURSOR type is as follows:

Syntax:
TYPE cursor_type_name IS REF CURSOR [RETURN return_type];

The following is an example of a cursor variable declaration.

DECLARE
    TYPE emp_cur_type IS REF CURSOR RETURN emp%ROWTYPE;
    rc_emp emp_cur_type;

Closing a Cursor Variable

Unlike static cursors, a cursor variable does not have to be closed before it can be re-opened again. The result set from the previous open will be lost. The example is completed with the addition of the CLOSE statement.

Syntax:
CLOSE cursor_name;

N.B:

  • Comparison operators cannot be used to test cursor variables for equality, inequality, null, or not null.
  • Null cannot be assigned to a cursor variable.
  • The value of a cursor variable cannot be stored in a database column.
  • Static cursors and cursor variables are not interchangeable. For example, a static cursor cannot be used in an OPEN FOR statement.

Permitted Cursor Variable Parameter Modes

Operation IN IN OUT OUT
OPEN No Yes No
FETCH Yes Yes No
CLOSE Yes Yes No

Create Country Table

SQL Code:
CREATE TABLE COUNTRIES
  (
    C_NAME  VARCHAR2(15 BYTE)
  );

Insert Data into Country Table

SQL Code:
REM INSERTING into COUNTRIES
Insert into COUNTRIES (C_NAME) values ('Poland');
Insert into COUNTRIES (C_NAME) values ('Germany');
Insert into COUNTRIES (C_NAME) values ('United States');
Insert into COUNTRIES (C_NAME) values ('Portugal');
Insert into COUNTRIES (C_NAME) values ('Czech Republic');
Insert into COUNTRIES (C_NAME) values ('China');
Insert into COUNTRIES (C_NAME) values ('Slovakia');
Insert into COUNTRIES (C_NAME) values ('Slovenia');

Procedure using ref cursor

create or replace
PROCEDURE p_Get_Country (
    p_CountryName     IN VARCHAR2
    )
  AS
  rc_Country_Search  SYS_REFCURSOR;
  v_query            VARCHAR2(30000) := NULL;
  rows_fetched       number;
  TYPE t_tab IS TABLE OF COUNTRIES%ROWTYPE;
  rec_tab t_tab;
BEGIN
  if (p_CountryName is not null) then
    v_query := 'SELECT C_NAME FROM COUNTRIES 
                where UTL_MATCH.JARO_WINKLER_SIMILARITY
                (C_NAME,'|| '''' || to_char(p_CountryName) || ''''  || ') > 60';
  else
    v_query := 'SELECT C_NAME FROM COUNTRIES';
  end if;

  OPEN  rc_Country_Search FOR v_query;
  FETCH rc_Country_Search BULK COLLECT INTO rec_tab;
  rows_fetched := rc_Country_Search%ROWCOUNT;
  --Print Data to the console
  dbms_output.put_line('--------------------------------');
  FOR i IN 1..rows_fetched LOOP
      dbms_output.put_line('Country Name -> '      ||  rec_tab(i).C_NAME||CHR( 13 ) || CHR( 10 ));
  END LOOP;
  dbms_output.put_line('--------------------------------');
  CLOSE rc_Country_Search;
END p_Get_Country;

Out put 1

Set serveroutput on
DECLARE
  RC_COUNTRY_SEARCH SYS_REFCURSOR;
BEGIN
  P_GET_COUNTRY(
    P_COUNTRYNAME => null
  );
END;
--------------------------------
Country Name -> Poland
Country Name -> Germany
Country Name -> United States
Country Name -> Portugal
Country Name -> Czech Republic
Country Name -> China
Country Name -> Slovakia
Country Name -> Slovenia
--------------------------------

Out put 2

Set serveroutput on
DECLARE
  RC_COUNTRY_SEARCH SYS_REFCURSOR;
BEGIN
  P_GET_COUNTRY(
    P_COUNTRYNAME => 'Slov'
  );
END;
--------------------------------
Country Name -> Slovakia
Country Name -> Slovenia
--------------------------------

Procedure for Ref Cursor population and return through out parameter

create or replace
PROCEDURE p_Get_Country2 (
    p_CountryName     IN VARCHAR2,
    rc_Country_Search  OUT SYS_REFCURSOR
    )
  AS
  v_query         VARCHAR2(30000) := NULL;
  TYPE t_tab IS TABLE OF COUNTRIES%ROWTYPE;
  rec_tab t_tab;
BEGIN
  if (p_CountryName is not null) then
    v_query := 'SELECT C_NAME FROM COUNTRIES
                where UTL_MATCH.JARO_WINKLER_SIMILARITY
                (C_NAME,'|| '''' || to_char(p_CountryName) || ''''  || ') > 60';
  else
    v_query := 'SELECT C_NAME FROM COUNTRIES';
  end if;

  OPEN  rc_Country_Search FOR v_query;

END p_Get_Country2;

Populate Ref cursor variable in C#.Net Console base application using ADO.NET

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OracleClient;
using System.Data;

namespace TEST_ODP
{
    class Program
    {
        static void Main(string[] args)
        {
            // create connection
            OracleConnection conn = new OracleConnection("Data Source=orcl;User;Password=test;");
            // create the command for the stored procedure
            OracleCommand cmd = new OracleCommand();

            Console.WriteLine("Please input your searching keyword.");
            string str = Console.ReadLine();

            cmd.Connection = conn;
            cmd.CommandText = "p_Get_Country2";
            cmd.CommandType = CommandType.StoredProcedure;

            // add the parameters for the stored procedure including the REF CURSOR
            // to retrieve the result set
            cmd.Parameters.Add("p_CountryName", OracleType.VarChar).Value = str.ToString();
            cmd.Parameters.Add("rc_Country_Search", OracleType.Cursor).Direction = ParameterDirection.Output;

            // open the connection and create the DataReader
            conn.Open();
            OracleDataReader dr = cmd.ExecuteReader();

            // output the results and close the connection.
            while (dr.Read())
            {
                for (int i = 0; i < dr.FieldCount; i++)
                    Console.Write(dr[i].ToString() + ";");
                Console.WriteLine();
            }
            conn.Close();
            Console.ReadLine();
        }
    }
}
Categories: Ref Cursor Tags:

Manual Cleanup process and Uninstall Oracle for Windows system

February 16, 2010 Leave a comment
  1. Uninstall all Oracle components using the Oracle Universal Installer (OUI).
  2. Delete the HKEY_LOCAL_MACHINE/SOFTWARE/ORACLE key which contains registry entries for all Oracle products by using regedit.
  3. Delete any references to Oracle services/components in the following registry location: HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/. Looks for key entries that starts with “Ora” which are obviously related to Oracle.
  4. Reboot the workstation.
  5. Delete the ORACLE_BASE directory. (i.e C:\Oracle)
  6. Delete the C:\Program Files\Oracle directory.
  7. Empty the temp directory.
  8. Empty the recycle bin.
Categories: How To, Uninstall Oracle

utl_match package for string matching

February 15, 2010 1 comment

There are four functions included in the package utl_match use different methods to compare a source string and destination string, and return an assessment of what it would take to turn the source string into the destination string.

Source: $ORACLE_HOME/rdbms/admin/utlmatch.sql

Oracle added the UTL_MATCH package in Version 10gRelease 2 to compare strings. The four functions included in the package use different methods to compare a source string and destination string, and return an assessment of what it would take to turn the source into the destination string. The functions are broken down into two categories. The categories are actually the algorithms employed to analyze the strings.

Levenshtein Distance

The Levenshtein Distance (LD) algorithm, commonly called the Edit Distance (ED) algorithm, is the older of the two supported methods. It measures the distance between the source and destination strings. By distance, we’re referring to the number of changes required to turn the source string into the destination string.

Jaro-Winkler

The Jaro-Winkler algorithm is the second category of algorithms used in UTL_ MATCH. These functions take the same two arguments, but instead of simply calculating the number of steps required to change the source string to the destination string, it determines how closely the two strings agree with each other. The algorithm also tries to take into account the possibility of a data entry error when determining similarity.

Procedures/Functions

edit_distance

Returns the number of changes required to turn the source string into the destination string using the Levenshtein Distance algorithm.

function edit_distance returns binary_integer (
 s1    in        varchar2,
 s2    in        varchar2       
);

edit_distance_similarity

Returns an integer between 0 and 100, where 0 indicates no similarity at all and 100 indicates a perfect match.

function edit_distance_similarity returns binary_integer (
 s1    in        varchar2,
 s2    in        varchar2       
);

jaro_winkler

Instead of simply calculating the number of steps required to change the source string to the destination string returns similarity based on Jaro-Winkler distance algorithm, determines how closely the two strings agree with each other and tries to take into account the possibility of a data entry error.

function jaro_winkler returns binary_double (
 s1    in       varchar2,
 s2    in       varchar2       
);

jaro_winkler_similarity

Returns an integer between 0 and 100, where 0 indicates no similarity at all and 100 indicates a perfect match but tries to take into account possible data entry errors.

function jaro_winkler_similarity returns binary_integer (
 s1    in                 varchar2,
 s2    in                 varchar2       
);

Example 1:

SQL> SELECT UTL_MATCH.EDIT_DISTANCE('espresso', 'expresso')
  2    AS DISTANCE
  3  FROM DUAL;

  DISTANCE
----------
         1

SQL> SELECT UTL_MATCH.EDIT_DISTANCE_SIMILARITY('espresso', 'expresso')
  2    AS DISTANCE
  3  FROM DUAL;

  DISTANCE
----------
        88

SQL> SELECT UTL_MATCH.JARO_WINKLER('espresso', 'expresso')
  2    AS DISTANCE
  3  FROM DUAL;

  DISTANCE
----------
 9.25E-001

SQL> SELECT UTL_MATCH.JARO_WINKLER_SIMILARITY ('espresso', 'expresso')
  2    AS DISTANCE
  3  FROM DUAL;

  DISTANCE
----------
        92

Example 2:

CREATE TABLE TEST
( 
        test_id        number primary key, 
        test_name      varchar2(20), 
        test_date      date
);  

INSERT INTO TEST values(1, 'Sony CD Player', '20-FEB-2010');
INSERT INTO TEST values(2, 'Sony CD Player', '24-FEB-2010');
INSERT INTO TEST values(3, 'Pioneer DVD Player', '25-FEB-2010');
INSERT INTO TEST values(4, 'Sony CD Player', '25-FEB-2010');
INSERT INTO TEST values(5, 'Bose Speaker', '22-FEB-2010');
INSERT INTO TEST values(6, 'Tascam CD Burner', '25-FEB-2010');
INSERT INTO TEST values(7, 'Nikon digital camera', '22-FEB-2010');
INSERT INTO TEST values(8, 'Canon digital camera', '26-FEB-2010');

Commit;

Select TEST_ID,TEST_NAME,TEST_DATE
FROM TEST
WHERE  UTL_MATCH.JARO_WINKLER_SIMILARITY(test_name,'dogotal') > 60;

TEST_ID                TEST_NAME            TEST_DATE
---------------------- -------------------- -------------------------
7                      Nikon digital camera 22-FEB-00
8                      Canon digital camera 26-FEB-00

Categories: DBMS_PACKEGE, UTL_MATCH Tags:

How to Insert and Update ampercent(‘&’) character in the Oracle table

February 6, 2010 Leave a comment
SQL> CREATE TABLE TEST ( TEST_ID  NUMBER,   TEST_DATA   VARCHAR2(50));
Table created.

To Insert or Update & into character field do the follow

SQL> show ESCAPE
escape OFF
SQL> Set ESCAPE "/"
SQL> show ESCAPE
escape "/" (hex 2f)

Now Insert Into the Test Table

SQL> INSERT INTO TEST (TEST_ID,TEST_DATA) VALUES (1,'Hospital /& Healthcare');

1 row created. 

Now Update Into the Test Table

SQL> UPDATE TEST
 2  Set TEST_DATA = 'Outsourcing /& Offshoring'
 3  WHERE TEST_ID = 1;

1 row updated.

Use the 10g Quoting mechanism:

Syntax q'[QUOTE_CHAR]Text[QUOTE_CHAR]'

N.B: Make sure that the QUOTE_CHAR doesnt exist in the text.

SELECT q’{This is Oracle’s ‘quoted’ text field & I like Oracle}’ FROM DUAL;
SQL> INSERT INTO TEST (TEST_ID,TEST_DATA) VALUES (2,q'{ Aviation & Aerospace}');

1 row created.

SQL> UPDATE TEST
 2  Set TEST_DATA = q'{Information Technology & Services}'
 3  WHERE TEST_ID = 2;

1 row updated.
SQL> Select * from test;

 TEST_ID    TEST_DATA
---------- --------------------------------------------------
 1    Outsourcing & Offshoring
 2    Information Technology & Services

Partition Table In Oracle

January 26, 2010 1 comment

What is Partition Table?

Decompose a table or index into smaller, more manageable pieces, called partitions. Each partition of a table or index must have the same logical attributes, such as column names, datatypes, and constraints, but each partition can have separate physical attributes such as pctfree, pctused, and tablespaces.

Partition Key

Each row in a partitioned table is unambiguously assigned to a single partition. The partition key is a set of from 1 to 16 columns that determines the partition for each row.

Sub Partition

Partitions created within partitions. They are just partitions themselves and there is nothing special about them.

Composite Partitioning

Composite partitioning is a combination of other partitioning methods. Oracle currently supports range-hash and range-list composite partitioning.

Interval Partitioning

Interval partitioning is an extension to range partitioning in which, beyond a point in time, partitions are defined by an interval. Interval partitions are automatically created by the database when data is inserted into the partition.

Partitioning Methods

There are several partitioning methods offered by Oracle Database:

1.    Range partitioning
2.    Hash partitioning
3.    List partitioning
4.    Composite range-hash partitioning
5.    Composite range-list partitioning

Range partitioning

Must specify the following three things when range partitions in created:

· Partitioning method: range
· Partitioning column(s)
· Partition descriptions identifying partition bounds
SQL Code:
CREATE TABLE sales
    (
        invoice_no NUMBER,
        sale_year  INT NOT NULL,
        sale_month INT NOT NULL,
        sale_day   INT NOT NULL
    )
 PARTITION BY RANGE (sale_year, sale_month, sale_day)
    (
        PARTITION sales_pA VALUES LESS THAN (1999, 04, 01) TABLESPACE tsa,
        PARTITION sales_pB VALUES LESS THAN (1999, 07, 01) TABLESPACE tsb,
        PARTITION sales_pC VALUES LESS THAN (1999, 10, 01) TABLESPACE tsc,
        PARTITION sales_pD VALUES LESS THAN (2000, 01, 01) TABLESPACE tsd
    );

In this example there is a table creates four partitions, one for each quarter of sales.

Partitioning column(s): sale_year, sale_month, and sale_day

Partition descriptions identifying partition bounds:

The VALUES LESS THAN clause determines the partition bound: rows with partitioning key values that compare less than the ordered list of values specified by the clause are stored in the partition.

Portion Name Tablespace
sales_pA tsa
sales_pB tsb
sales_pC tsc
sales_pD tsd

Use range partitioning to map rows to partitions based on ranges of column values. This type of partitioning is useful when dealing with data that has logical ranges into which it can be distributed; for example, months of the year. Performance is best when the data evenly distributes across the range. If partitioning by range causes partitions to vary dramatically in size because of unequal distribution, you may want to consider one of the other methods of partitioning.

To get Information about the portion table run the following query

select partition_position, partition_name, high_value
from dba_tab_partitions
where table_name = 'SALES' order by 1;
 

Adding a Partition to a Range-Partitioned Table

ALTER TABLE sales
  ADD PARTITION jan2010 VALUES LESS THAN ( '01-FEB-2010' )
  TABLESPACE tsx;

Hash partitioning

Must specify the following three things when range partitions in created:

· Partitioning method: hash
· Partitioning column(s)
· Number of partitions or individual partition descriptions

SQL Code:
create table customer (
        customer_id            number,
        customer_name          varchar2(20)
)
partition by hash (customer_id)
partitions 4
store in (gear1, gear2, gear3, gear4);
 

The above example creates a hash-partitioned table. The partitioning column is customer_id, four partitions are created and assigned system generated names, and they are placed in four named tablespaces (gear1, gear2, gear3, gear4)

Adding a Partition to a Hash-Partitioned table

ALTER TABLE customer
      ADD PARTITION customer_id TABLESPACE gear5;

List partitioning

Must specify the following three things when range partitions in created:

· Partitioning method: List
· Partitioning column(s)
· Partition descriptions, each specifying a list of literal values (a value list),
   Which are the discrete values of the partitioning column
   that qualify a row to be included in the partition

SQL Code:
create table sales (
        product_id     number,
        trans_amt      number,
        sales_dt       date,
        state_code     varchar2(2)
)
partition by list (state_code)
(
partition ct             values ('CT'),
partition ca             values ('CA'),
partition ny_vm_nj       values ('NY', 'VM', 'NJ'),
partition def            values (default)
);

Use list partitioning when you require explicit control over how rows map to partitions. You can specify a list of discrete values for the partitioning column in the description for each partition. This is different from range partitioning, where a range of values is associated with a partition, and from hash partitioning, where the user has no control of the row to partition mapping.

Adding a Partition to a List-Partitioned Table

The following statement illustrates adding a new partition to a list-partitioned table. In this example physical attributes and NOLOGGING are specified for the partition being added.

ALTER TABLE sales
   ADD PARTITION hi VALUES ('HI')
      STORAGE (INITIAL 20K NEXT 20K) TABLESPACE tbs_3
      NOLOGGING;

Composite range-hash partitioning

Must specify the following three things when range partitions in created:

· Partitioning method: range
· Partitioning column(s)
· Partition descriptions identifying partition bounds
 
· Subpartitioning method: hash
· Subpartitioning column(s)
· Number of subpartitions for each partition or descriptions of subpartitions

SQL Code:
CREATE TABLE scubagear (
        equipno NUMBER,
        equipname VARCHAR(32),
        price NUMBER
        )
 PARTITION BY RANGE (equipno) SUBPARTITION BY HASH(equipname)
    SUBPARTITIONS 8 STORE IN (ts1, ts2, ts3, ts4)
        (
        PARTITION p1 VALUES LESS THAN (1000),
        PARTITION p2 VALUES LESS THAN (2000),
        PARTITION p3 VALUES LESS THAN (MAXVALUE)
        );

In this example, three range partitions are created, each containing eight subpartitions. Because the subpartitions are not named, system generated names are assigned, but the STORE IN clause distributes them across the 4 specified tablespaces (ts1, ts2, ts3, ts4).

Range-hash partitioning partitions data using the range method, and within each partition, subpartitions it using the hash method. These composite partitions are ideal for both historical data and striping, and provide improved manageability of range partitioning and data placement, as well as the parallelism advantages of hash partitioning.

The partitions of a range-hash partitioned table are logical structures only, as their data is stored in the segments of their subpartitions. As with partitions, these subpartitions share the same logical attributes. Unlike range partitions in a range-partitioned table, the subpartitions cannot have different physical attributes from the owning partition, although they are not required to reside in the same tablespace

Adding a Partition to a range-hash Table

ALTER TABLE sales
      ADD PARTITION q1_2000 VALUES LESS THAN (2000, 04, 01)
      SUBPARTITIONS 8 STORE IN tbs5;

Composite range-list partitioning

Must specify the following three things when range partitions in created:

· Partitioning method: range
· Partitioning column(s)
· Partition descriptions identifying partition bounds
 
· Subpartitioning method: list
· Subpartitioning column
· Subpartition descriptions, each specifying a list of literal values (a value list),
  which are the discrete values of the subpartitioning
  column that qualify a row to be included in the subpartition
SQL Code:
CREATE TABLE quarterly_regional_sales
      (deptno number, item_no varchar2(20),
       txn_date date, txn_amount number, state varchar2(2))
  TABLESPACE ts4
  PARTITION BY RANGE (txn_date)
    SUBPARTITION BY LIST (state)
      (PARTITION q1_1999 VALUES LESS THAN (TO_DATE('1-APR-1999','DD-MON-YYYY'))
         (SUBPARTITION q1_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q1_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q1_1999_northeast VALUES ('NY', 'VM', 'NJ'),
          SUBPARTITION q1_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q1_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q1_1999_southcentral VALUES ('OK', 'TX')
         ),
       PARTITION q2_1999 VALUES LESS THAN ( TO_DATE('1-JUL-1999','DD-MON-YYYY'))
         (SUBPARTITION q2_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q2_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q2_1999_northeast VALUES ('NY', 'VM', 'NJ'),
          SUBPARTITION q2_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q2_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q2_1999_southcentral VALUES ('OK', 'TX')
         ),
       PARTITION q3_1999 VALUES LESS THAN (TO_DATE('1-OCT-1999','DD-MON-YYYY'))
         (SUBPARTITION q3_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q3_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q3_1999_northeast VALUES ('NY', 'VM', 'NJ'),
          SUBPARTITION q3_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q3_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q3_1999_southcentral VALUES ('OK', 'TX')
         ),
       PARTITION q4_1999 VALUES LESS THAN ( TO_DATE('1-JAN-2000','DD-MON-YYYY'))
         (SUBPARTITION q4_1999_northwest VALUES ('OR', 'WA'),
          SUBPARTITION q4_1999_southwest VALUES ('AZ', 'UT', 'NM'),
          SUBPARTITION q4_1999_northeast VALUES ('NY', 'VM', 'NJ'),
          SUBPARTITION q4_1999_southeast VALUES ('FL', 'GA'),
          SUBPARTITION q4_1999_northcentral VALUES ('SD', 'WI'),
          SUBPARTITION q4_1999_southcentral VALUES ('OK', 'TX')
         )
      );

Like the composite range-hash partitioning method, the composite range-list partitioning method provides for partitioning based on a two level hierarchy. The first level of partitioning is based on a range of values, as for range partitioning; the second level is based on discrete values, as for list partitioning. This form of composite partitioning is well suited for historical data, but lets you further group the rows of data based on unordered or unrelated column values.

Dropping a Table Partition

Use one of the following statements to drop a table partition or subpartition:

  • ALTER TABLE ... DROP PARTITION to drop a table partition
  • ALTER TABLE ... DROP SUBPARTITION to drop a subpartition of a range-list partitioned table

Partition Indexes

There is two types of indexes on partitioned tables:

  • Local Index
  • Global Index

Local Index: The index is partitioned in exactly the same way as the base table. For instance, you can create a local index on the TRANS_AMOUNT column of the TRANS table as follows:

create index in_trans_01
on trans (trans_amount)
local;

This creates a range-partitioned index, on the TRANS_DT column, the same way the TRANS table is partitioned. All the index entries for a specific partition, such as Y05Q1, will exist only inside the corresponding partition of the index.

Global Index: The index can span all partitions in the base table. For example, suppose there is a primary key on TRANS, on the TRANS_ID column. The primary key can be anywhere inside the table, across all the partitions. In this case, the index entries of a partition of the table may exist outside the corresponding partition of the index. For such a situation, create a global index, as follows:

alter table trans
add constraint pk_trans
primary key (trans_id)
using index global;
Reference:
http://www.oracle.com/technology/oramag/oracle/06-sep/o56partition.html
http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10739/partiti.htm

Create directory in Oracle

January 3, 2010 2 comments

Directories must be created if external tables are used. Created directories are shown in either dba_directories or all_directories. There is no user_directories. When a directory has been created, the read and write object privileges can be granted on it

Related Data Dictionary Objects

dir$    all_directories         ku$_directory_t
        dba_directories         ku$_directory_view

System Privileges

GRANT create any directory TO <user_name>;
GRANT drop any directory TO <user_name>;
Syntax: CREATE OR REPLACE DIRECTORY <directory_name> AS '<operating_system_path>';
SQL Code:
create or replace directory attachment_dir as '/u02';

Select * from  all_directories
Where directory_name = 'ATTACHMENT_DIR'

Granting Privileges to a Directory

grant read, write on directory attachment_dir to cpdb;

SELECT grantor, grantee, table_schema, table_name, privilege
FROM all_tab_privs
WHERE table_name = 'ATTACHMENT_DIR';

Set UTL_FILE_DIR using ALTER SYSTEM command

alter system set UTL_FILE_DIR = '/u02/attachment_dir' scope=spfile;

OS Commend to create a directory

[oracle@vasdbsrv u02]$ mkdir /u02/attachment_dir
[oracle@vasdbsrv u02]$ ls -la
total 36
drwxrwxr-x   5 oracle oinstall  4096 Dec  8 13:08 .
drwxr-xr-x  26 root   root      4096 Dec  7 09:10 ..
drwxr-xr-x   2 oracle oinstall  4096 Dec  8 13:08 attachment_dir
drwxrwxr-x   2 oracle oinstall 16384 Nov 12 15:35 lost+found
drwxr-x---   3 oracle oinstall  4096 Nov 12 10:50 oradata

PLSQL Code to read or write a file to the directory

Source: {ORACLE_HOME}/rdbms/admin/utlfile.sql
declare
  f utl_file.file_type;
begin
  f := utl_file.fopen('ATTACHMENT_DIR', myfile.txt', 'w');
  utl_file.put_line(f, 'line test 1: text-1');
  utl_file.put_line(f, 'line test 2: text-2');
  utl_file.fclose(f);
end;
/

Drop Directory

Syntax: DROP DIRECTORY <directory_name>;
SELECT *
FROM dba_directories;

DROP DIRECTORY 'ATTACHMENT_DIR;

Optimize Oracle UNDO Parameters

January 2, 2010 Leave a comment

Data Concurrency and Read Consistency

ROLLBACK or UNDO is the backbone of the READ CONSISTENCY mechanism provided by Oracle. Multi-User Data Concurrency and Read Consistency mechanism make Oracle stand tall in Relational Database Management Systems (RDBMS) world.

Starting in Oracle9i, rollback segments are re-named undo logs. Traditionally transaction undo information was stored in Rollback Segments until a commit or rollback statement was issued, at which point it was made available for overlaying.

Best of all, automatic undo management allows the DBA to specify how long undo information should be retained after commit, preventing “snapshot too old” errors on long running queries.

This is done by setting the UNDO_RETENTION parameter.  The default is 900 seconds (5 minutes), and you can set this parameter to guarantee that Oracle keeps undo logs for extended periods of time.

Rather than having to define and manage rollback segments, you can simply define an Undo tablespace and let Oracle take care of the rest. Turning on automatic undo management is easy.  All you need to do is create an undo tablespace and set UNDO_MANAGEMENT = AUTO.

UNDO_RETENTION is a parameter in the init.ora initialization parameters file that specifies the time period in seconds for which a system retains undo data for committed transactions. The flashback query can go upto the point of time specified as a value in the UNDO_RETENTION parameter.

The properties of the UNDO_RETENTION parameter are mentioned below:

  • Parameter type – Integer
  • Default value – 900
  • Range of values – 0 to 232 – 1
  • Syntax – ALTER SYSTEM SET UNDO_RETENTION = < seconds >;

However it is worth to tune the following important parameters

1. The size of the UNDO tablespace
2. The UNDO_RETENTION parameter

Calculate UNDO_RETENTION for given UNDO Tabespace

You can choose to allocate a specific size for the UNDO tablespace and then set the UNDO_RETENTION parameter to an optimal value according to the UNDO size and the database activity. If your disk space is limited and you do not want to allocate more space than necessary to the UNDO tablespace, this is the way to proceed. The following query will help you to optimize the UNDO_RETENTION parameter:

Optimal Undo Retention =
           Actual Undo Size / (DB_BLOCK_SIZE × UNDO_BLOCK_REP_ESC)

Because these following queries use the V$UNDOSTAT statistics, run the queries only after the database has been running with UNDO for a significant and representative time.

Actual Undo Size

SELECT SUM(a.bytes) "UNDO_SIZE"
FROM v$datafile a,
       v$tablespace b,
       dba_tablespaces c
WHERE c.contents = 'UNDO'
   AND c.status = 'ONLINE'
   AND b.name = c.tablespace_name
   AND a.ts# = b.ts#;

Undo Blocks per Second

SELECT MAX(undoblks/((end_time-begin_time)*3600*24)) "UNDO_BLOCK_PER_SEC"
FROM v$undostat;

DB Block Size

SELECT TO_NUMBER(value) "DB_BLOCK_SIZE [KByte]"
FROM v$parameter
WHERE name = 'db_block_size';

Optimal Undo Retention Calculation

Formula:
Optimal Undo Retention = 
           Actual Undo Size / (DB_BLOCK_SIZE × UNDO_BLOCK_REP_ESC)

Using Inline Views, you can do all calculation in one query

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

Calculate Needed UNDO Size for given Database Activity

If you are not limited by disk space, then it would be better to choose the UNDO_RETENTION time that is best for you (for FLASHBACK, etc.). Allocate the appropriate size to the UNDO tablespace according to the database activity:

Formula:
Undo Size = Optimal Undo Retention × DB_BLOCK_SIZE × UNDO_BLOCK_REP_ESC

Using Inline Views, you can do all calculation in one query

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

Automatic Undo Retention Tuning

Oracle 10g automatically tunes undo retention to reduce the chances of “snapshot too old” errors during long-running queries. The UNDO_RETENTION parameter is used to set a low retention time threshold which the system will attempt to achieve. In the event of any undo space constraints the system will prioritize DML operations over undo retention meaning the low threshold may not be achieved. If the undo retention threshold must be guaranteed, even at the expense of DML operations, the RETENTION GUARANTEE clause can be set against the undo tablespace during or after creation:

Reset the undo low threshold.

ALTER SYSTEM SET UNDO_RETENTION = 2400;

Guarantee the minimum threshold is maintained.

ALTER TABLESPACE undotbs1 RETENTION GUARANTEE;
 
SELECT tablespace_name, retention FROM dba_tablespaces;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       GUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.

Switch back to the default mode.

ALTER TABLESPACE undotbs1 RETENTION NOGUARANTEE;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       NOGUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.

The Undo Advisor PL/SQL Interface

Oracle Database provides an Undo Advisor that provides advice on and helps automate the establishment of your undo environment. You activate the Undo Advisor by creating an undo advisor task through the advisor framework. The following example creates an undo advisor task to evaluate the undo tablespace. The name of the advisor is ‘Undo Advisor‘. The analysis is based on Automatic Workload Repository snapshots, which you must specify by setting parameters START_SNAPSHOT and END_SNAPSHOT. In the following example, the START_SNAPSHOT is “1″ and END_SNAPSHOT is “2″.

DECLARE
   tid    NUMBER;
   tname  VARCHAR2(30);
   oid    NUMBER;
   BEGIN
   DBMS_ADVISOR.CREATE_TASK('Undo Advisor', tid, tname, 'Undo Advisor Task');
   DBMS_ADVISOR.CREATE_OBJECT(tname, 'UNDO_TBS', null, null, null, 'null', oid);
   DBMS_ADVISOR.SET_TASK_PARAMETER(tname, 'TARGET_OBJECTS', oid);
   DBMS_ADVISOR.SET_TASK_PARAMETER(tname, 'START_SNAPSHOT', 1);
   DBMS_ADVISOR.SET_TASK_PARAMETER(tname, 'END_SNAPSHOT', 2);
   DBMS_ADVISOR.execute_task(tname);
end;
Source : http://www.oracle.com/technology/oramag/code/tips2004/032904.html

Automatic Undo Retention Tuning

Oracle 10g automatically tunes undo retention to reduce the chances of “snapshot too old” errors during long-running queries. The UNDO_RETENTION parameter is used to set a low retention time threshold which the system will attempt to achieve. In the event of any undo space constraints the system will prioritize DML operations over undo retention meaning the low threshold may not be achieved. If the undo retention threshold must be guaranteed, even at the expense of DML operations, the RETENTION GUARANTEE clause can be set against the undo tablespace during or after creation:

Reset the undo low threshold.

ALTER SYSTEM SET UNDO_RETENTION = 2400;

Guarantee the minimum threshold is maintained.

ALTER TABLESPACE undotbs1 RETENTION GUARANTEE;
 
SELECT tablespace_name, retention FROM dba_tablespaces;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       GUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.

Switch back to the default mode.

ALTER TABLESPACE undotbs1 RETENTION NOGUARANTEE;
 
TABLESPACE_NAME                RETENTION
------------------------------ -----------
SYSTEM                         NOT APPLY
UNDOTBS1                       NOGUARANTEE
SYSAUX                         NOT APPLY
TEMP                           NOT APPLY
USERS                          NOT APPLY
 
5 rows selected.

How to backup and restore the Oracle Control File

January 2, 2010 Leave a comment

There are two approaches to take Backup of control file in Oracle:

  • Backing it up in a binary format
  • Backing it up in a human readable format
Syntax: 
alter database backup controlfile to ['filename' | trace]

This command comes in two versions. One backs up the control file in a binary format while the other backs it up in a human readable form. It is required if the database is running in archive log mode and a structural change was made to the database.

Backing it up in a binary format:

You can generate a binary image of the Control File

SQL Code: 
alter database backup controlfile
               to '/some/arbitrary/path';
alter database backup controlfile
               to '/some/arbitrary/path' reuse;

Backing it up in a human readable format:

You generate a text file script which will re-generate a Control File when run as a SQL script. The file name will be something like ‘ora_<some numbers>.trc’

SQL Code:
alter database backup controlfile to trace;

Check udump directory for text based controlfile.

Syntax:
alter database backup controlfile to trace
               as '/some/arbitrary/path';
alter database backup controlfile to trace
               as '/some/arbitrary/path' reuse;

If the human readable form is chosen, the file can be made usable if the comments at the beginning are removed and replaced with a connect / as sysdba. If the init.ora file is not at its default location, it has to be appended with a pfile=…. in the line containing a startup.

Restore the control file

The trouble starts when you attempt to restore the binary version of the Control File backup. Because it was an exact, binary copy of a Control File, its SCN number will not agree with the SCN in the headers of all the data files -basically, the Master Clock is out of whack. You therefore have to issue the following command

RECOVER DATABASE USING BACKUP CONTROLFILE;

It tells the system not to pay too much attention to the SCN of the Control File. Unfortunately, after you issue that command (and following any recovery that it might cause to take place), you must open the database with the following command:

ALTER DATABASE OPEN RESETLOGS;

You can also use RMAN script to restore and recover control file to all locations specified in the parameter file then restore the database, using that control file:

SQL Code
STARTUP NOMOUNT;
RUN
{
  ALLOCATE CHANNEL c1 DEVICE TYPE sbt;
  RESTORE CONTROLFILE;
  ALTER DATABASE MOUNT;
  RESTORE DATABASE;
}

Restore control file to default location:

The default location is defined by CONTROL_FILES parameter of pfile/spfile. If you don’t specify any location while restoring your control file then the control file will be restored to the location set by CONTROL_FILES parameter.

RMAN Code: 
RMAN> SET DBID 7887865467
RMAN> RUN {
      RESTORE CONTROLFILE FROM AUTOBACKUP;
     }

Restore of the Control File from Control File Autobackup

For the use who are using  recovery catalog, you can restore your control file from an autobackup. The database must be in a NOMOUNT state. And you have to set DBID. RMAN uses the autobackup format and DBID to determine where to find for the control file autobackup.

RMAN Code:
RMAN> SET DBID 7887865467
RMAN> RUN {
        SET CONTROLFILE AUTOBACKUP FORMAT
        FOR DEVICE TYPE DISK TO 'autobackup_format';
        RESTORE CONTROLFILE FROM AUTOBACKUP;
      }

Restoring a Control File When Using a Recovery Catalog

The recovery catalog contains a complete record of the backups of Database, including backups of the control file. Therefore, It is not necessary to mention the DBID or control file autobackup format.

RMAN Code:
$rman TARGET / CATALOG cpdb/cpdb
RMAN> RESTORE CONTROLFILE;

Restore of the Control File From a Known Location

If you know the backuppiece of controlfile or any copy then simply you can use,

RMAN Code: 
RMAN> RESTORE CONTROLFILE from 'filename';

Restore of the Control File to a New Location

In prior cases RMAN restore the control file to the location specified by CONTROL_FILES parameter of the spfile or pfile.If you want to restore the control file to another location use,

RMAN Code:
RMAN> RESTORE CONTROLFILE TO '<new_location>';

It is also possible to change CONTROL_FILES parameter and then perform RESTORE CONTROLFILE to change location.

Limitations When Using a Backup Control File

After Complete the restore and recover the control file  using a backup control file, It is mandatory  run RECOVER DATABASE and perform an OPEN RESETLOGS on the database. Where SCN is change.

 

I have Take a backup using RMAN in following way.

Backup Control file using RMAN

 
RMAN nocatalog target /
RMAN> BACKUP CURRENT CONTROLFILE;

Scenario: I have deleted the control files now tiring to start the database; I have got the following error message successfully.

SQL> STARTUP
ORACLE instance started.

Total System Global Area  167772160 bytes
Fixed Size                  1247900 bytes
Variable Size              67110244 bytes
Database Buffers           96468992 bytes
Redo Buffers                2945024 bytes
ORA-00205: error in identifying control file, check alert log for more info

Recover Control file using RMAN

RMAN nocatalog target /
RMAN> Restore controlfile from autobackup;
Or
RMAN> RUN {
RESTORE CONTROLFILE FROM AUTOBACKUP;
}
RMAN> alter database mount;
RMAN> recover database;
RMAN> alter database open resetlogs;


Scenario: incomplete database recovery
SQL> Select name from v$database;
 
NAME
---------
CJPROD
 
SQL> select status from v$instance;
 
STATUS
------------
MOUNTED
 
SQL> alter database open;
alter database open
*
ERROR at line 1:
ORA-01113: file 1 needs media recovery
ORA-01110: data file 1: 'C:\ORACLE\PRODUCT\10.2.0\ORADATA\CJPROD\SYSTEM01.DBF'
 
 
SQL> alter database open resetlogs;
alter database open resetlogs
*
ERROR at line 1:
ORA-01139: RESETLOGS option only valid after an incomplete database recovery
 
 
SQL> recover database using backup controlfile until cancel
ORA-00279: change 551523 generated at 03/13/2011 00:15:03 needed for thread 1
ORA-00289: suggestion :
C:\ORACLE\PRODUCT\10.2.0\FLASH_RECOVERY_AREA\CJPROD\ARCHIVELOG\2011_03_13\O1_MF_1_3_%U_.ARC
ORA-00280: change 551523 for thread 1 is in sequence #3
 
Specify log: {<RET>=suggested | filename | AUTO | CANCEL}
C:\oracle\product\10.2.0\oradata\cjprod\REDO02.LOG
Log applied.
Media recovery complete.
SQL> alter database open resetlogs;
 
Database altered.
 

Related Link: http://tamimdba.wordpress.com/category/oracle10g/controlfile-auto-backup/

RMAN Retore & Recover

December 16, 2009 Leave a comment

Use the RMAN RESTORE command to restore the following types of files from copies on disk or backups on other media:

· Database (all datafiles)
· Tablespaces
· Control files
· Archived redo logs
· Server parameter files

Automates the procedure for restoring files. When you issue a RESTORE command, RMAN restore the correct backups and copies to either:

· The default location, overwriting the old files with the same name
· A new location, which you can specify with the SET NEWNAME command

RMAN Backup Clause Syntax

   RECOVER [DEVICE TYPE deviceSpecifier [, deviceSpecifier]...]
               recoverObject [recoverOptionList];

Steps for media recovery Using RMAN

Step 01:

Mount or open the database. Mount the database when performing whole database recovery, or open the database when performing online tablespace recovery.

STARTUP FORCE MOUNT;

Step 02:

To perform incomplete recovery, use the SET UNTIL command to specify the time, SCN, or log sequence number at which recovery terminates. Alternatively, specify the UNTIL clause on the RESTORE and RECOVER commands.

Step 03:

Restore the necessary files with the RESTORE command.

Step 04:

Recover the datafiles with the RECOVER command.

Step 05:

Place the database in its normal state. For example, open it or bring recovered tablespaces online.

Restore and recover the whole database

RMAN> STARTUP FORCE MOUNT;
RMAN> RESTORE DATABASE;
RMAN> RECOVER DATABASE;
RMAN> ALTER DATABASE OPEN;

Script Code:
STARTUP NOMOUNT;
RUN
{
   ALLOCATE CHANNEL c1 DEVICE TYPE sbt;
   RESTORE DATABASE;
   ALTER DATABASE MOUNT;   
   RECOVER DATABASE;
}

Restore and recover a tablespace

RMAN> SQL 'ALTER TABLESPACE users OFFLINE';
RMAN> RESTORE TABLESPACE users;
RMAN> RECOVER TABLESPACE users;
RMAN> SQL 'ALTER TABLESPACE users ONLINE';

Restore and recover a datafile

RMAN> SQL 'ALTER DATABASE DATAFILE 32 OFFLINE';
RMAN> RESTORE DATAFILE 32;
RMAN> RECOVER DATAFILE 32;
RMAN> SQL 'ALTER DATABASE DATAFILE 32 ONLINE';

Restore and recover the Control file from Backup

Restore the control file, (to all locations specified in the parameter file) then restore the database, using that control file:

STARTUP NOMOUNT;
RUN
{
   ALLOCATE CHANNEL c1 DEVICE TYPE sbt;
   RESTORE CONTROLFILE;
   ALTER DATABASE MOUNT;
   RECOVER DATABASE;
}

Create a new control file

If all control file copies are lost, you can create a new control file using the NORESETLOGS option and open the database after doing media recovery. An existing standby database instance can generate the script to create a new control file by using the following statement

SQL> ALTER DATABASE BACKUP CONTROLFILE TO TRACE NORESETLOGS;

Recovery from the Loss of an Online Redo Log File

To add a new member to a redo log group, issue the following statement:

SQL> ALTER DATABASE ADD LOGFILE MEMBER 'log_file_name' REUSE TO GROUP n

Disaster Recovery

In a disaster situation where all files are lost you can only recover to the last SCN in the archived redo logs. Beyond this point the recovery would have to make reference to the online redo logs which are not present. Disaster recovery is therefore a type of incomplete recovery.

Step 01: Connect to RMAN

$rman catalog=rman/rman@orcl target=sys/oracle@orcl

Step 02: Recover the control file if needed.

RMAN> startup nomount;
RMAN> restore controlfile;
RMAN> alter database mount;

Step 03: Collect the last SCN using SQL*Plus as SYS

SQL> SELECT archivelog_change#-1 FROM v$database;

ARCHIVELOG_CHANGE#-1
--------------------
             1203813

Step 04: Restore and Recover database using RMAN.

 
RMAN> run {
        set until scn 1203813;
        restore database;
        recover database;
        alter database open resetlogs;
        }

Restore Validation

Restore Validation confirms that a restore could be run, by confirming that all database files exist and are free of physical and logical corruption, this does not generate any output.

RMAN> RESTORE DATABASE VALIDATE;
Categories: RMAN Recover Tags:

Backup Using RMAN

December 16, 2009 Leave a comment

Types of Files that can be Backup Using RMAN

The BACKUP command can back up of Database, which includes all data files as well as the current control file and current server parameter.

Following type of backup can be perform by RMAN

  • Tablespaces (except for locally-managed temporary tablespaces)
  • Current datafiles
  • Current control file
  • Archived redo logs
  • Current server parameter file
  • Backup sets

RMAN does not back up the following:

  • Online redo logs
  • Transported tablespaces before they have been made read/write
  • Client-side initialization parameter files or noncurrent server parameter files

RMAN Backup Clause Syntax

   BACKUP FULL Options
   BACKUP FULL AS (COPY | BACKUPSET) Options
   BACKUP INCREMENTAL LEVEL [=] integer Options
   BACKUP INCREMENTAL LEVEL [=] integer AS (COPY | BACKUPSET) Options
   BACKUP AS (COPY | BACKUPSET) Options
   BACKUP AS (COPY | BACKUPSET) (FULL | INCREMENTAL LEVEL [=] integer) Options
Database Backup

Back up the database, and then the control file which contains a record of the backup

RMAN> BACKUP DATABASE;
RMAN> BACKUP CURRENT CONTROLFILE;
Data files Backup
RMAN> BACKUP AS BACKUPSET DATAFILE
        'ORACLE_HOME/oradata/users01.dbf',
        'ORACLE_HOME/oradata/tools01.dbf';
Backup all data files in the database

Bit-for-bit copies, created on disk

RMAN> BACKUP AS COPY DATABASE;
Backup archive logs
RMAN> BACKUP ARCHIVELOG COMPLETION TIME BETWEEN 'SYSDATE-30' AND 'SYSDATE';
Backup tablespace
RMAN> BACKUP TABLESPACE system, users, tools;
Backup controlfile
RMAN> BACKUP CURRENT CONTROLFILE TO '/backup/cntrlfile.copy';
Backup Server parameter file
RMAN> BACKUP SPFILE;
Backup everything
RMAN> BACKUP BACKUPSET ALL;

Create a consistent backup and keep the backup for 1 year:

Exempt from the retention policy

RMAN> SHUTDOWN;
RMAN> STARTUP MOUNT;
RMAN> BACKUP DATABASE UNTIL 'SYSDATE+365' NOLOGS;

Backup Validation confirms that a backup could be run, by confirming that all database files exist and are free of physical and logical corruption, this does not generate any output.

RMAN> BACKUP VALIDATE DATABASE ARCHIVELOG ALL;

Multilevel Incremental Backups

RMAN can create multilevel incremental backups. Each incremental level is denoted by an integer, for example, 0, 1, 2, and so forth. A level 0 incremental backup, which is the base for subsequent incremental backups, copies all blocks containing data. The only difference between a level 0 backup and a full backup is that a full backup is never included in an incremental strategy.

If no level 0 backup exists when you run a level 1 or higher backup, RMAN makes a level 0 backup automatically to serve as the base.

The benefit of performing multilevel incremental backups is that RMAN does not back up all block all of the time.

Differential Incremental Backups

In a differential level n incremental backup, RMAN backs up all blocks that have changed since the most recent backup at level n or lower.

For example, in a differential level 2 backup, RMAN determines which level 2 or level 1 backup occurred most recently and backs up all blocks modified after that backup. If no level 1 is available, RMAN copies all blocks changed since the base level 0 backup. If no level 0 backup is available, RMAN makes a new base level 0 backup for this file.

Use Command for incremental Level Backup

RMAN> backup incremental level 0 database tag="SUNDAY";
RMAN> backup incremental level 3 database tag="MONDAY";
RMAN> backup incremental level 3 database tag="TUESDAY";
RMAN> backup incremental level 3 database tag="WEDNESDAY";
RMAN> backup incremental level 2 database tag="THURSDAY";
RMAN> backup incremental level 3 database tag="FRIDAY";
RMAN> backup incremental level 3 database tag="SATURDAY";

Cumulative Incremental Backups

RMAN provides an option to make cumulative incremental backups at level 1 or greater. In a cumulative level n backup, RMAN backs up all the blocks used since the most recent backup at level n-1 or lower.

For example, in cumulative level 2 backups, RMAN determines which level 1 backup occurred most recently and copies all blocks changed since that backup. If no level 1 backups are available, RMAN copies all blocks changed since the base level 0 backup.

Cumulative incremental backups reduce the work needed for a restore by ensuring that you only need one incremental backup from any particular level. Cumulative backups require more space and time than differential backups, however, because they duplicate the work done by previous backups at the same level.

Use Command for Cumulative Level Backup

RMAN> backup incremental level=0 database tag='base';
RMAN> backup incremental level=2 cumulative database tag='monday';
RMAN> backup incremental level=2 cumulative database tag='tuesday';
RMAN> backup incremental level=2 cumulative database tag='wednesday';
RMAN> backup incremental level=2 cumulative database tag='thursday';
RMAN> backup incremental level=2 cumulative database tag='friday';
RMAN> backup incremental level=2 cumulative database tag='saturday';
RMAN> backup incremental level=1 cumulative database tag='weekly'

You can view your incremental Backup Details by using following Query

SQL Code: 
select  incremental_level,
        incremental_change#,
        checkpoint_change#,
        blocks
from    v$backup_datafile;

RMAN Configuration

December 16, 2009 Leave a comment

A complete high availability and disaster recovery strategy requires dependable data backup, restore, and recovery procedures. Oracle Recovery Manager (RMAN), a command-line and Enterprise Manager-based tool, is the Oracle-preferred method for efficiently backing up and recovering your Oracle database. RMAN is designed to work intimately with the server, providing block-level corruption detection during backup and restore. RMAN optimizes performance and space consumption during backup with file multiplexing and backup set compression, and integrates with Oracle Secure Backup and third party media management products for tape backup.

RMAN takes care of all underlying database procedures before and after backup or restore, freeing dependency on OS and SQL*Plus scripts. It provides a common interface for backup tasks across different host operating systems, and offers features not available through user-managed methods, such as parallelization of backup/recovery data streams, backup files retention policy, and detailed history of all backups.

Step 01: Create tablepsace to hold repository

#sqlplus sys/sys_password@orcl AS SYSDBA

SQL>  CREATE TABLESPACE "RMAN"
DATAFILE 'C:\oracle\product\10.2.0\oradata\orcl\RMAN.DBF' SIZE 6208K REUSE
AUTOEXTEND ON NEXT 64K MAXSIZE 32767M
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO;

Step 02: Create user RMAN Schema owner for the backup and recovery using RMAN.

SQL>  CREATE USER rman IDENTIFIED BY rman
TEMPORARY TABLESPACE temp
DEFAULT TABLESPACE rman
QUOTA UNLIMITED ON rman;

Step 03: Grant recovery_catalog_owner to RMAN user

SQL>  GRANT connect, resource, recovery_catalog_owner TO rman;

Step 04: Now connect to the RMAN and Create Repository catalog

$rman catalog=rman/rman@orcl

Recovery Manager: Release 10.2.0.1.0 - Production on Wed Dec 16 19:55:32 2009

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

connected to recovery catalog database

RMAN> create catalog tablespace "RMAN";

recovery catalog created

Step 05: Register Database Each database to be backed up by RMAN must be registered

$rman catalog=rman/rman@orcl target=sys/oracle@orcl

Recovery Manager: Release 10.2.0.1.0 - Production on Wed Dec 16 20:01:00 2009

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

connected to target database: ORCL (DBID=1223903242)
connected to recovery catalog database

RMAN> register database;

database registered in recovery catalog
starting full resync of recovery catalog
full resync complete

RMAN> exit

Recovery Manager complete.
We have done!!!! The configuration of RMAN in our Database

Some Basic Parameter of RMAN

Retention Policy:

This instructs RMAN on the backups that are eligible for deletion. For example: A retention policy with redundancy 2 would mean that two backups – the latest and the one prior to that – should be retained. All other backups are candidates for deletion.

Default Device Type:

This can be “disk” or “sbt” (system backup to tape). We will backup to disk and then have our OS backup utility copy the completed backup, and other supporting files, to tape.

Control files Auto backup:

This can be set to “on” or “off”. When set to “on”, RMAN takes a backup of the control file AND server parameter file each time a backup is performed. Note that “off” is the default

Parallelism:

This tells RMAN how many server processes you want dedicated to performing the backups.

Device Type Format:

This specifies the location and name of the backup files. We need to specify the format for each channel. The “%U” ensures that Oracle appends a unique identifier to the backup file name. The MAXPIECESIZE attribute sets a maximum file size for each file in the backup set.

Control files Auto backup Format:

This tells RMAN where the controlfile backup is to be stored. The “%F” in the file name instructs RMAN to append the database identifier and backup timestamp to the backup filename. The database identifier, or DBID, is a unique integer identifier for the database.

For example, one can turn off control file auto backups by issuing:
RMAN> configure controlfile autobackup off;

Show All Command

Any of the above parameters can be changed using the commands displayed by the “show all” command.

RMAN> show all;

Mechanism of Restore and Recovery operation

RMAN> RESTORE DATABASE;

RMAN> RECOVER DATABASE;

Resynchronized Catalog

The recovery catalog should be resynchronized on a regular basis so that changes to the database structure and presence of new archive logs is recorded. Some commands perform partial and full resyncs implicitly, but if you are in doubt you can perform a full resync using the following command.

RMAN> resync catalog;

starting full resync of recovery catalog
full resync complete

RECYCLE BIN

December 16, 2009 Leave a comment

Oracle has introduced the RECYCLE BIN which is a logical entity to hold all the deleted objects and works exactly like the recycle bin provided in Windows operating system for example. All the deleted objects are kept n the recycle bin; these objects can be retrieved from the recycle bin or deleted permanently by using the PURGE command. Either an individual object like a table or an index can be deleted from the recycle bin

Related Data Dictionary Objects

·         recyclebin$
·         dba_recyclebin   
·         recyclebin 
·         user_recyclebin

user_recyclebin and dba_recyclebin are use for recovery using flashback

 
SQL> SELECT name, value
FROM v$parameter
WHERE name LIKE 'recyc%';

NAME             VALUE       
----------------------                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
recyclebin       on       
 

How to Use Recycle Bin in Oracle 10g

Starting and stopping the recyclebin

Syntax: 
ALTER SYSTEM SET recyclebin=<OFF | ON> SCOPE=<BOTH | MEMORY | SPFILE>;

By default recyclebin is set to on

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

SQL> select OBJECT_NAME, ORIGINAL_NAME, TYPE from  dba_recyclebin;
no rows selected
SQL> drop table scott.emp;
Table dropped.

SQL> select OBJECT_NAME, ORIGINAL_NAME, TYPE from dba_recyclebin;
OBJECT_NAME                              ORIGINAL_NAME        TYPE
-----------------------------------------------------------------
BIN$iSsOuMCxThKB65n/ep2Y5g==$0    PK_EMP        INDEX
BIN$JsuRtykaSpOd8XLplx1/vA==$0    EMP           TABLE

To recover the emp table issue the following command

Syntax:
FLASHBACK TABLE <table_name> TO BEFORE DROP {RENAME TO <new_table_name>};

SQL> flashback table scott.emp to before drop;
Flashback complete.
Now emp table is restored from recyclebin.

You can also rename the table during the time of restore

SQL> flashback table scott.emp to before drop
     RENAME TO scott.emp2; 

To clear the recycle bin issue the following command

Syntax:
PURGE TABLE <recycle_bin_name>;
 
SQL> PURGE TABLE scott.emp;
 
Table purged.

Remove Recycle Bin Objects by Tablespace and User

Syntax:
PURGE TABLESPACE <tablespace_name> 
USER <schema_name>;
 
SQL Code:
PURGE TABLESPACE users USER scott;

Clear full recycilebin

Syntax:
PURGE RECYCLEBIN

Empty Everything in All Recycle Bins

SQL Code:
PURGE dba_recyclebin;
 
 
Categories: RECYCLE BIN Tags:

Flashback Recovery

December 16, 2009 Leave a comment

Flashback query is a powerful and useful feature introduced in Oracle 9i, and enhanced greatly in Oracle 10g, that can help us recover data, lost or corrupted, due to human error. One big advantages of using flashback over point-in-time recovery is that for the latter not only transactions from the time of error to the current time would be lost but also the system will be unavailable for the duration of the recovery. For flashback query, on the other hand, there will be no down time needed and repair or recovery is less labor and time intensive than what it used to be in earlier versions of Oracle. With the new features like Recycle Bin, Flashback databases and Flashback Drop in Oracle 10g, the flashback capability introduced in 9i has been improved tremendously now turning a small feature into a powerful tool in the new Oracle releases.

Type of flashback recovery:

  • Flashback Database (We can revert database at a past time)
  • Flashback Drop (Reverses the effects of a DROP TABLE statement)
  • Flashback Table (Reverses a table to its state at a previous point in time)
  • Flashback Query (We can specify a target time and then run queries, viewing results and recover from an unwanted change)
  • Flashback Transaction Query (We can view changes made by a transaction during a period of time.)

Requirement for Flashback:

  • Database must be in Archive log mode
  • Must have flash recovery area enable

According to the Oracle documentation, Flashback technologies are applicable in repairing the following user errors.

  • Erroneous or malicious DROP TABLE statements
  • Erroneous or malicious update, delete or insert transactions
  • Erroneous or malicious batch job or wide-spread application errors

Dependent Objects

  • V_$FLASHBACK_DATABASE_LOG
  • V_$FLASHBACK_DATABASE_LOGFILE
  • V_$FLASHBACK_DATABASE_STAT
  • GV_$FLASHBACK_DATABASE_LOG
  • GV_$FLASHBACK_DATABASE_LOGFILE
  • GV_$FLASHBACK_DATABASE_STAT

Syntax:

Syntax base on SCN: 
SCN FLASHBACK [STANDBY] DATABASE [<database_name>]
TO [BEFORE] SCN <system_change_number> 

Syntax base on TIMESTAMP: 
TIMESTAMP FLASHBACK [STANDBY] DATABASE [<database_name>]
TO [BEFORE] TIMESTMP <system_timestamp_value> 

Syntax base on RESTORE POINT: 
RESTORE POINT FLASHBACK [STANDBY] DATABASE [<database_name>]
TO [BEFORE] RESTORE POINT <restore_point_name>

Flashback Syntax Elements

How to OFF Flashback

Syntax:
ALTER DATABASE FLASHBACK OFF;

How to ON Flashback

Syntax:
ALTER DATABASE FLASHBACK ON;

Start flashback on a tablespace

ALTER TABLESPACE <tablespace_name> FLASHBACK ON;

Stop flashback on a tablespace

ALTER TABLESPACE <tablespace_name> FLASHBACK OFF;

Initialization Parameters

Setting the location of the flashback recovery area

db_recovery_file_dest=/oracle/flash_recovery_area

Setting the size of the flashback recovery area

db_recovery_file_dest_size=2147483648

Setting the retention time for flashback files (in minutes) — 2 days

db_flashback_retention_target=2880

Set Retention Target

Syntax:
ALTER SYSTEM SET db_flashback_retention_target = <number_of_minutes>;
SQL Code:
alter system set DB_FLASHBACK_RETENTION_TARGET = 2880;

How to Enable Flashback

Flashback query is not enabled by default and must be turned on in following sequence. We will set retention to 10 hours (600 minutes) and set recovery size up to 2 GB in file “/recovery/flashback

Step 01: Verify the Database in flash back mode and the retention_target.

SQL> SELECT flashback_on, log_mode
FROM v$database;
FLASHBACK_ON       LOG_MODE
------------------ ------------
NO                 ARCHIVELOG

Step 02: Shutdown the database and start in exclusive mode

SQL> shutdown immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup mount exclusive;
ORACLE instance started.

Total System Global Area  612368384 bytes
Fixed Size                  1250452 bytes
Variable Size             268438380 bytes
Database Buffers          339738624 bytes
Redo Buffers                2940928 bytes
Database mounted.

Step 03: Enable the Archive log and Set the DB_FLASHBACK_RETENTION_TARGET, DB_RECOVERY_FILE_DEST_SIZE and DB_RECOVERY_FILE_DEST.

Flash Recovery Area created by the DBA, is the allocation of space on the disk to hold all the recovery related files in one, centralized place. Flash Recovery Area contains the Flashback Logs, Redo Archive logs, backups files by RMAN and copies of control files. The destination and the size of the recovery area are setup using the db_recovery_file_dest and b_recovery_file_dest_size initializatin parameters.

SQL> alter database archivelog;

Database altered.

SQL> alter system set DB_FLASHBACK_RETENTION_TARGET=600;

System altered.

SQL> alter system set DB_RECOVERY_FILE_DEST_SIZE=2G;

System altered.

SQL> alter system set DB_RECOVERY_FILE_DEST=
‘C:\oracle\product\10.2.0\flash_recovery_area\ORCL\FLASHBACK’;

System altered.

N.B: For UNIX system issue the following command

alter system set DB_RECOVERY_FILE_DEST=‘/recovery/flashback’;

Step 04: On the Flash back and open the database.

SQL> alter database flashback on;

System altered.

SQL> alter database open;

Step 05: Now Verify the Database flashback mode.

SQL> SELECT flashback_on, log_mode
FROM v$database;
FLASHBACK_ON       LOG_MODE
------------------ ------------
YES                ARCHIVELOG
SQL> SELECT name, value
FROM gv$parameter
WHERE name LIKE ‘%flashback%’;
NAME                              VALUE
---------------------------------------
db_flashback_retention_target      600
SQL> SELECT estimated_flashback_size
FROM gv$flashback_database_log;
ESTIMATED_FLASHBACK_SIZE
------------------------
22835200

How to Recover Database from Flashback recovery area

Step 01: Find the Current SCN and Flashback time.

SQL> SELECT current_scn
  2  FROM v$database;

CURRENT_SCN
-----------
    1143033

SQL> SELECT oldest_flashback_scn,oldest_flashback_time
  2  FROM gv$flashback_database_log;

OLDEST_FLASHBACK_SCN OLDEST_FL
-------------------- ---------
             1141575 16-DEC-09

Step 02: Grant flashback to the user.

So that user can create a restore point and flashback

GRANT flashback any table TO <user_name>;

Step 03: Shutdown the database and start in exclusive mode.

SQL> SHUTDOWN immediate;

SQL> startup mount exclusive;

Step 04: Be sure to substitute your SCN and issue the following command

SQL> FLASHBACK DATABASE TO SCN <SCN Number>;

Flashback complete.

Or If restore point create by the user

FLASHBACK DATABASE TO RESTORE POINT <RESTORE POINT>;

Or flashback using TIMESTAMP

FLASHBACK DATABASE TO TIMESTAMP (SYSDATE-1/24);
FLASHBACK DATABASE TO TIMESTAMP Timestamp ‘2009-11-05 14:00:00’;
FLASHBACK DATABASE TO TIMESTAMP
                   TO_TIMESTAMP (‘2009-11-11 16:00:00’, ‘YYYY-MM-DD HH24:MI:SS’);

Step 05: Now open database using resetlogs

alter database open will fail

SQL> alter database open;
alter database open
*
ERROR at line 1:
ORA-01589: must use RESETLOGS or NORESETLOGS option for database open

alter database open resetlogs will be succeed

SQL> alter database open resetlogs;

Database altered.

Step 06: See the flashback status

SELECT *
FROM gv$flashback_database_stat;

INST_ID   BEGIN_TIME  END_TIME  FLASHBACK_DATA   DB_DATA  REDO_DATA ESTIMATED_FLASHBACK_SIZE
------- ------------ --------- --------------- --------- ---------- ------------------------
1         16-DEC-09   16-DEC-09 827392          9797632    130048                         0

Step 06: Now switch the log and use RMAN to clear the archive log following way

alter system switch logfile;

shutdown immediate;

startup mount exclusive;

alter database flashback off;

alter database noarchivelog;

alter database open;

SQL> SELECT flashback_on, log_mode
  2  FROM v$database;

FLASHBACK_ON       LOG_MODE
------------------ ------------
NO                 NOARCHIVELOG

Run rman to delete the archive log

$rman target sys/oracle@orcl

Recovery Manager: Release 10.2.0.1.0 - Production on Wed Dec 16 15:06:09 2009

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

connected to target database: ORCL (DBID=1223903242)

RMAN> crosscheck archivelog all;

RMAN> delete archivelog all;

RMAN> list archivelog all;

Note:

In RAC Database, flashback recovery area must be store is clustered file system or in ASM

Default retation target is 1440 (One Days).

If we want to retain flashback logs to perform a 48 hour flashback, set the retention target to 2880 minutes (2 days x 24 hours/day x 60 minutes/hour)

By default, flashback logs are generated for all permanent tablespaces

Important:

  • If we disable Flashback Database for a tablespace, then we must take its datafiles offline before running FLASHBACK DATABASE.
  • We can enable Flashback Database not only on a primary database, but also on a standby database.

Listener-Broken pipe

December 14, 2009 2 comments

I have successfully install Oracle on Linux, installed and configured my all Java and PHP application for a content Server and a SMS Gateway and everything is working fine. After several months later from an angry user saying that he cannot login to the application and the SMS getaway not working.

The error message indicates a problem connecting to the Oracle database. After some troubleshooting (lsntctl status) I have found the Oracle TNS listener is not running, I attempt to start it and get the following stack trace error:

[oracle@contentserver admin]$ lsnrctl start

LSNRCTL for Linux: Version 9.2.0.1.0 - Production on 14-DEC-2009 08:44:43

Copyright (c) 1991, 2002, Oracle Corporation.  All rights reserved.

Starting /u01/app/oracle/product/9.2.0.1.0/bin/tnslsnr: please wait...

TNS-12547: TNS:lost contact
 TNS-12560: TNS:protocol adapter error
  TNS-00517: Lost contact
   Linux Error: 32: Broken pipe

Then I have check with the SYS admin to only find out that nothing has changed with any of the network settings. Every this is ok.

This is one of those troubleshooting issues that can take several hours to track done. But as it turns out, the most common reason for this stack trace when attempting to start the listener is the log file for the listener ($ORACLE_HOME/network/log/listener.log) has reached its 2GB file size limit on Linux. To alleviate the problem, simply archive or delete the file and restart the listener.

How to solve this problem:

Switch to the network log directory

[oracle@contentserver log]$ cd /u01/app/oracle/product/9.2.0.1.0/network/log

See the size of the listener.log, here I have found 2.1 GB

[oracle@contentserver log]$ du -h listener.log
2.1G    listener.log

Copy the log file to the other directory if you need to backup this file for any kind of troubleshooting task.

[oracle@contentserver log]$ cp listener.log /home/oracle/

Then remove the file using OS command, to do this issue the following command.

[oracle@contentserver log]$ rm listener.log

Now start the listener service.

[oracle@contentserver log]$ lsnrctl start

DBMS_JOB package

December 13, 2009 1 comment

The DBMS_JOB package allows a user to schedule a job to run at a specified time.  A job is submitted to a job queue and runs at the specified time.  The user can also input a parameter that specifies how often the job should run.  A job can consist of any PL/SQL code.

Source: {ORACLE_HOME}/rdbms/admin/dbmsjob.sq

SNP Background Processes

SNP processes run in the background and implement database snapshots and job queues.  If an SNP process fails, Oracle restarts it without affecting the rest of the database.  An SNP process can run one job at a time with a maximum of ten SNP processes running simultaneously.  The INIT.ORA initialization file contains three parameters that control the behavior of the SNP processes:

Parameters Description
JOB_QUEUE_PROCESSES How many processes to start.  If set to zero, no jobs are executed. Default is 0.  Range is 0..1000.
JOB_QUEUE_INTERVAL (obsolete in 9i) How long an interval the process will sleep before checking for a new job. Default is 60 sec.  Range is 1..3600 sec
JOB_QUEUE_KEEP_CONNECTIONS Controls whether an SNP process closes any remote database connections. Default is False.  Range is True/False.

Job Owner

The person who submits a job to the job queue is considered the job’s owner. The job’s owner is the only one who can alter the job, force the job to run, or remove the job from the queue.  If you need to look up any information regarding a submitted job, DBA_JOBS and USER_JOBS contain a lot of information such as the job number, user, status, etc.

Dependencies

 job$            
·         dba_jobs      
·         all_jobs      
·         user_jobs
·         dba_jobs_running      
·         all_jobs_running      
·         user_jobs_running

Job Intervals

·         Execute daily          'SYSDATE + 1'
·         Execute once per week  'SYSDATE + 7'
·         Execute hourly         'SYSDATE + 1/24'
·         Execute every 10 min.  'SYSDATE + 10/1440'
·         Execute every 30 sec.  'SYSDATE + 30/86400'
·         Do not re-execute      NULL

Changing Scheduled Jobs

The DBMS_JOB.CHANGE procedure alters a specified job that has already been submitted to the job queue. The job description, the time at which the job will be run, the interval between executions of the job, and the instance and force of a job can all be altered.

Syntax:

DBMS_JOB.CHANGE (
 job       IN  BINARY_INTEGER,
 what      IN  VARCHAR2,
 next_date IN  DATE,
 interval  IN  VARCHAR2,
 instance  IN  BINARY_INTEGER DEFAULT NULL,
 force     IN  BOOLEAN DEFAULT FALSE);
job- Number of the job being run.
What – PL/SQL procedure to run.
next_date – Date of the next refresh.
interval – Date function evaluated immediately before the job starts running.
instance – When a job is submitted, specifies which instance can run the job.
This defaults to NULL, which indicates that instance affinity is not changed.
force – If this is FALSE, then the specified instance must be running.
Otherwise, the routine raises an exception.
If this is TRUE, then any positive integer is acceptable as the job instance.

SQL Code:
EXECUTE DBMS_JOB.CHANGE(1, null, sysdate+3, null);

Change the WHAT

The definition of a job can be altered by calling the DBMS_JOB.WHAT procedure.

Syntax:

 DBMS_JOB.CHANGE (
 job    IN  BINARY_INTEGER,
 what   IN  VARCHAR2);

SQL Code:

execute DBMS_JOB.WHAT(3,Begin SEND_MESSAGE(); End;');

Changing the Next Date

The DBMS_JOB.NEXT_DATE procedure alters the next execution time for a specified job.

Syntax:

DBMS_JOB.NEXT_DATE (JOB IN BINARY_INTEGER,
 NEXT_DATE  IN DATE);

SQL Code:

execute DBMS_JOB.NEXT_DATE(4,SYSDATE+3);

Changing the Interval

The DBMS_JOB.INTERVAL procedure alters the interval between executions for a specified job. 

Syntax:
DBMS_JOB.INTERVAL (job         IN  BINARY_INTEGER,
                   interval  IN  VARCHAR2); 

Assign job to RAC instance

Assign a specific RAC instance to execute a job:

Syntax:
dbms_job.instance(
job      IN BINARY_INTEGER,
instance IN BINARY_INTEGER,
force    IN BOOLEAN DEFAULT FALSE); 

SELECT instance_number FROM gv$instance;

SQL Code:
EXECUTE  DBMS_JOB.INSTANCE(job=>123, instance=>1);
 
SQL Code:
SELECT JOB,SUBSTR(WHAT,1,35),NEXT_DATE, NEXT_SEC,INTERVAL
FROM DBA_JOBS;

ISUBMIT

Submit a job with a user specified job number

Syntax:
dbms_job.isubmit (
job       IN BINARY_INTEGER,
what      IN VARCHAR2,
next_date IN DATE,
interval  IN VARCHAR2 DEFAULT 'NULL',
no_parse  IN BOOLEAN DEFAULT FALSE);

N.B: no_parse indicates whether to parse job PL/SQL at time of submission (FALSE) or execution (TRUE)

exec dbms_job.isubmit(4242, 'MYPROC', SYSDATE);
 
IS_JOBQ
dbms_job.is_jobq RETURN BOOLEAN;

SQL Code:
set serveroutput on

DECLARE
 b BOOLEAN;
BEGIN
  IF dbms_job.is_jobq THEN
    dbms_output.put_line('TRUE');
  ELSE
    dbms_output.put_line('FALSE');
  END IF;
END;
/

BROKEN Jobs

How a job becomes ‘broken’

  • Oracle has failed to successfully execute the job after 16 attempts.
    or
  • You have marked the job as broken, using the procedure DBMS_JOB.BROKEN

N.B:  Once a job has been marked as broken, Oracle will not attempt to execute the job until it is either marked not broken, or forced to be execute by calling the DBMS_JOB.RUN.
Syntax:
dbms_job.broken (
job       IN BINARY_INTEGER,
broken    IN BOOLEAN,
next_date IN DATE DEFAULT SYSDATE);

Run a job now

To force immediate job execution:

EXEC dbms_job.run(job_no);

Mark a job as not broken

If a job fails to successfully execute it will go into a broken state after 16 attempts. To reset the job use following command

EXEC dbms_job.broken(jobno, FALSE);

Monitor User jobs

See created jobs:

SQL Code:
SELECT  job, next_date,
        next_sec,
        failures,
        broken,
        SUBSTR(what,1,40) DESCRIPTION
FROM user_jobs; 

Jobs that are currently running:

SQL Code:
select
job                               j,
to_char ( last_date, 'hh24:mi:ss' ) last,
to_char ( this_date, 'hh24:mi:ss' ) this,
to_char ( next_date, 'hh24:mi:ss' ) next,
broken                            b,
failures                          f,
interval,
what
from user_jobs;

Remove a submitted job

Syntax: 
dbms_job.remove(job IN BINARY_INTEGER);
EXECUTE DBMS_JOB.REMOVE(jobno);

Example of DBMS_JOBS

--Job For Email 
declare
   jobno integer;
begin
   dbms_job.submit(
      job => jobno, 
           what => 'begin PROC_SEND_EMAIL_AT_11_45(); end;',
         --       provide resolution to the second
         --                midnight        hour of   minute of         units per day
         --             of current day    day to run         hr to run         ( 1 second )
      next_date => trunc(sysdate) + ((23 * (60*60) + ( 60*45)) * ( 1/(60*60*24))),
      interval =>  'trunc(sysdate + 1) + ((23 * (60*60) + ( 60*50)) * ( 1/(60*60*24)))'
   );
   commit;
end;
/

What Sessions are Running the Jobs

set linesize 250
col sid            for 9999     head 'Session|ID'
col spid                        head 'O/S|Process|ID'
col serial#        for 9999999  head 'Session|Serial#'
col log_user       for a10
col job            for 9999999  head 'Job'
col broken         for a1       head 'B'
col failures       for 99       head "fail"
col last_date      for a18      head 'Last|Date'
col this_date      for a18      head 'This|Date'
col next_date      for a18      head 'Next|Date'
col interval       for 9999.000 head 'Run|Interval'
col what           for a60
select j.sid,
s.spid,
s.serial#,
       j.log_user,
       j.job,
       j.broken,
       j.failures,
       j.last_date||':'||j.last_sec last_date,
       j.this_date||':'||j.this_sec this_date,
       j.next_date||':'||j.next_sec next_date,
       j.next_date - j.last_date interval,
       j.what
from (select djr.SID,
             dj.LOG_USER, dj.JOB, dj.BROKEN, dj.FAILURES,
             dj.LAST_DATE, dj.LAST_SEC, dj.THIS_DATE, dj.THIS_SEC,
             dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
        from dba_jobs dj, dba_jobs_running djr
       where dj.job = djr.job ) j,
     (select p.spid, s.sid, s.serial#
          from v$process p, v$session s
         where p.addr  = s.paddr ) s
 where j.sid = s.sid;

Viewing scheduled dbms_jobs

set linesize 250
col log_user       for a10
col job            for 9999999  head 'Job'
col broken         for a1       head 'B'
col failures       for 99       head "fail"
col last_date      for a18      head 'Last|Date'
col this_date      for a18      head 'This|Date'
col next_date      for a18      head 'Next|Date'
col interval       for 9999.000 head 'Run|Interval'
col what           for a60

select j.log_user,
     j.job,
     j.broken,
     j.failures,
     j.last_date||':'||j.last_sec last_date,
     j.this_date||':'||j.this_sec this_date,
     j.next_date||':'||j.next_sec next_date,
     j.next_date - j.last_date interval,
     j.what
from (select dj.LOG_USER, dj.JOB, dj.BROKEN, dj.FAILURES,
             dj.LAST_DATE, dj.LAST_SEC, dj.THIS_DATE, dj.THIS_SEC,
             dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
        from dba_jobs dj) j;

What Jobs are Actually Running

set linesize 250
col sid            for 9999     head 'Session|ID'
col log_user       for a10
col job            for 9999999  head 'Job'
col broken         for a1       head 'B'
col failures       for 99       head "fail"
col last_date      for a18      head 'Last|Date'
col this_date      for a18      head 'This|Date'
col next_date      for a18      head 'Next|Date'
col interval       for 9999.000 head 'Run|Interval'
col what           for a60
select j.sid,
       j.log_user,
       j.job,
       j.broken,
       j.failures,
       j.last_date||':'||j.last_sec last_date,
       j.this_date||':'||j.this_sec this_date,
       j.next_date||':'||j.next_sec next_date,
       j.next_date - j.last_date interval,
       j.what
from (select djr.SID,
             dj.LOG_USER, dj.JOB, dj.BROKEN, dj.FAILURES,
             dj.LAST_DATE, dj.LAST_SEC, dj.THIS_DATE, dj.THIS_SEC,
             dj.NEXT_DATE, dj.NEXT_SEC, dj.INTERVAL, dj.WHAT
        from dba_jobs dj, dba_jobs_running djr
       where dj.job = djr.job ) j;
Categories: DBMS_JOB Tags:

Oracle UTL_SMTP And UTIL_MAIL Service

December 10, 2009 4 comments

The UTL_MAIL or UTL_SMPT package is introduced in Oracle 10g and it is easier to use when compared to UTL_SMTP.  In order to use Oracle UTL_MAIL package we have to set a new init.ora parameter or spinit.ora if database running in spfile “SMTP_OUT_SERVER” set to outgoing mail server. Make sure that there is a getaway for the outgoing mail.

Step 1: Send Mail in Linux Server

[root@vasdbsrv mail]# rpm -qa |grep sendmail
sendmail-8.13.1-3.RHEL4.5
sendmail-cf-8.13.1-3.RHEL4.5

To verify the mail service running in the local host

[oracle@vasdbsrv ~]$ telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
220 vasdbsrv.ring.com.bd ESMTP Sendmail 8.13.1/8.13.1; Thu, 10 Dec 2009 14:54:51 +0600

If sendmail not installed then install it by using following command.

$ rpm –ivh sendmail

Step 2: Make sure the send mail service run on kick start.

[root@vasdbsrv mail]# chkconfig –list |grep sendmail

sendmail        0:off   1:off   2:on    3:on    4:on    5:on    6:off

Add service in checkcofig:

$ chkconfig  --add sendmail
$ chkconfig  --level 345 sendmail on

Step 3: Configure the /etc/mail/sendmail.cf

If you are running mail server in private IP

[oracle@vasdbsrv ~]$ vi /etc/mail/sendmail.cf
# "Smart" relay host (may be null)
DSmail.dnsgroup.net

Step 4: Configure /etc/resolv.conf

[root@vasdbsrv mail]# vi /etc/resolv.conf
search ring.com.bd
nameserver 203.188.191.5

Follow the simple steps to send an email using UTL_MAIL package

Step 5: Install UTL_MAIL or UTL_SMTP package

To install the UTL_MAIL and UTL_SMTP package, run the below files as user “SYS”

Source:

$ORACLE_HOME/rdbms/admin/utlmail.sql
$ORACLE_HOME/rdbms/admin/utlsmtp.sql
$ORACLE_HOME/rdbms/admin/prvtmail.plb

Step 6: Grant permissions

Grants the execute permission on UTL_MAIL privilege to PUBLIC or the user which will use the package.

Run the beow command as user “SYS”

 SQL> GRANT EXECUTE ON utl_smtp TO PUBLIC;
 -or-
 SQL> GRANT EXECUTE ON utl_smtp TO <USER NAME>;

Step 7: Set SMTP_OUT_SERVER parameter

 SQL> ALTER SYSTEM SET smtp_out_server='smtp.domain.com' SCOPE=both;

Step 8: Create procedure to send email

 create or replace PROCEDURE send_mail_smtp
 (   sender     IN VARCHAR2,
 recipient  IN VARCHAR2,
 subject    IN VARCHAR2,
 message    IN LONG
 )
IS
   mailhost     VARCHAR2(30) := 'localhost';  -- -- host mail address
   mail_conn    utl_smtp.connection ;
   crlf VARCHAR2( 2 ):= CHR( 13 ) || CHR( 10 );
   mesg long;
BEGIN
   mail_conn := utl_smtp.open_connection(mailhost, 25);

   mesg:= 'Date: ' || TO_CHAR( SYSDATE, 'dd Mon yy hh24:mi:ss' ) || crlf ||
          'From:  <'||sender||'>' || crlf ||
          'Subject: '||subject || crlf ||
          'To: '||recipient || crlf ||
          '' || crlf || message;
   utl_smtp.helo(mail_conn, mailhost);
   utl_smtp.mail(mail_conn, sender);
   utl_smtp.rcpt(mail_conn, recipient);
   utl_smtp.data(mail_conn, mesg);
   utl_smtp.quit(mail_conn);

   EXCEPTION
      WHEN UTL_SMTP.INVALID_OPERATION THEN
       dbms_output.put_line(' Invalid Operation in Mail attempt using UTL_SMTP.');
      WHEN UTL_SMTP.TRANSIENT_ERROR THEN
       dbms_output.put_line(' Temporary e-mail issue - try again');
      WHEN UTL_SMTP.PERMANENT_ERROR THEN
       dbms_output.put_line(' Permanent Error Encountered.'); 
END;

To Run the SEND_MAIL_SMTP run the following code.

BEGIN
SEND_MAIL_SMTP(
'tamimdba@yahoo.com',           --Sender
'tamimdba@gmail.com',           --Recipient
'Test Mail',                    --Subject
'Send From Oracle10g Database'  --Message
);
END;
PL/SQL procedure successfully completed.
Follow

Get every new post delivered to your Inbox.

Join 26 other followers