Showing posts with label Oracle Database. Show all posts
Showing posts with label Oracle Database. Show all posts

Monday, January 19, 2015

How to select only duplicate records?

This is a guideline to select:

First ways:
 
Select State FROM Area
GROUP BY State
Having COUNT(*) > 1
 
Second ways:
 
 
SELECT DISTINCT a1.State
FROM AREA a1
JOIN AREA a2
  ON a1.AreaId != a2.AreaId  -- assume there is a Key to join on
  AND a1.State = a2.State    -- and such that different Areas with same State

Tuesday, August 19, 2014

Insert all values of a table into another table in SQL

The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "*" though:
 

INSERT INTO new_table (Foo, Bar, Fizz, Buzz) SELECT Foo, Bar, Fizz, Buzz FROM initial_table -- optionally WHERE ...

 
 
I'd better clarify this because for some reason this post is getting a few down-votes.
The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.
You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists.

Tuesday, March 25, 2014

deinstall oracle 11g on linux

From 11gR2, oracle provide us an deinstall tool. With that now we can easily remove oracle binaries.

Below is the step:
node1[oracle]_orcl> cd $ORACLE_HOME
node1[oracle]_orcl> cd deinstall 
node1[oracle]_orcl> ls -ltr
-rwxr-xr-x 1 oracle dba 32343 Dec 16 2009  sshUserSetup.sh
-rw-r--r-- 1 oracle dba 409   Aug 18 2010  readme.txt
-rw-r--r-- 1 oracle dba 3466  Aug 18 2010  deinstall.xml
-rwxr-xr-x 1 oracle dba 9780  May 10 2011  bootstrap.pl
-rwxr-xr-x 1 oracle dba 18475 Jun 9  2011  deinstall.pl
drwxr-xr-x 2 oracle dba 4096  Feb 20 11:15 response
drwxr-xr-x 2 oracle dba 4096  Feb 20 11:15 jlib
-rwxr-xr-x 1 oracle dba 9655  Feb 20 11:17 deinstall

node1[oracle]_orcl> ./deinstall
Checking for required files and bootstrapping ...
Please wait ...
Location of logs /tmp/deinstall2012-04-19_01-29-47AM/logs/
############ ORACLE DEINSTALL & DECONFIG TOOL START ############
############### CHECK OPERATION START #######################
## [START] Install check configuration ##
Checking for existence of the Oracle home location /orcl/oracle/product/11.2.0.3
Oracle Home type selected for deinstall is: Oracle Single Instance Database
Oracle Base selected for deinstall is: /orcl/oracle
Checking for existence of central inventory location /orcl/oracle/oraInventory
Checking for sufficient temp space availability on node(s) : 'node1'
## [END] Install check configuration ##
Network Configuration check config START
Network de-configuration trace file location: /tmp/deinstall2012-04-19_01-29-47AM/logs/netdc_check2012-04-19_01-30-16-AM.log
Specify all Single Instance listeners that are to be de-configured [LISTENER_orcl]:Network Configuration check config END
Database Check Configuration START
Database de-configuration trace file location: /tmp/deinstall2012-04-19_01-29-47AM/logs/databasedc_check2012-04-19_01-31-56-AM.log
Use comma as separator when specifying list of values as input
Specify the list of database names that are configured in this Oracle home [orcl]:
###### For Database 'orcl' ######
Single Instance Database
The diagnostic destination location of the database: /orcl/oracle/dump01/oracle/orcl/diag/rdbms/orcl
Storage type used by the Database:
The details of database(s) orcl have been discovered automatically. Do you still want to modify the details of orcl database(s)? [n]:
Database Check Configuration END
Enterprise Manager Configuration Assistant START
EMCA de-configuration trace file location: /tmp/deinstall2012-04-19_01-29-47AM/logs/emcadc_check2012-04-19_01-32-05-AM.log
Checking configuration for database orcl
Enterprise Manager Configuration Assistant END
Oracle Configuration Manager check START
OCM check log file location : /tmp/deinstall2012-04-19_01-29-47AM/logs//ocm_check1221.log
Oracle Configuration Manager check END
######################### CHECK OPERATION END #########################
####################### CHECK OPERATION SUMMARY #######################
Oracle Home selected for deinstall is: /orcl/oracle/product/11.2.0.3
Inventory Location where the Oracle home registered is: /orcl/oracle/oraInventory
Following Single Instance listener(s) will be de-configured: LISTENER_orcl
The following databases were selected for de-configuration : orcl
Database unique name : orcl
Storage used :
No Enterprise Manager configuration to be updated for any database(s)
No Enterprise Manager ASM targets to update
No Enterprise Manager listener targets to migrate
Checking the config status for CCR
Oracle Home exists and CCR is configured
CCR check is finished
Do you want to continue (y - yes, n - no)? [n]: y
A log of this session will be written to: '/tmp/deinstall2012-04-19_01-29-47AM/logs/deinstall_deconfig2012-04-19_01-30-14-AM.out'
Any error messages from this session will be written to: '/tmp/deinstall2012-04-19_01-29-47AM/logs/deinstall_deconfig2012-04-19_01-30-14-AM.err'
######################## CLEAN OPERATION START ########################
Enterprise Manager Configuration Assistant START
EMCA de-configuration trace file location: /tmp/deinstall2012-04-19_01-29-47AM/logs/emcadc_clean2012-04-19_01-32-05-AM.log
Updating Enterprise Manager ASM targets (if any)
Updating Enterprise Manager listener targets (if any)
Enterprise Manager Configuration Assistant END
Database de-configuration trace file location: /tmp/deinstall2012-04-19_01-29-47AM/logs/databasedc_clean2012-04-19_01-32-09-AM.log
Database Clean Configuration START orcl
This operation may take few minutes.
Database Clean Configuration END orcl
Network Configuration clean config START
Network de-configuration trace file location: /tmp/deinstall2012-04-19_01-29-47AM/logs/netdc_clean2012-04-19_01-33-54-AM.log
De-configuring Single Instance listener(s): LISTENER_orcl
De-configuring listener: LISTENER_orcl
Stopping listener: LISTENER_orcl
Warning: Failed to stop listener. Listener may not be running.
Deleting listener: LISTENER_orcl
Listener deleted successfully.
Listener de-configured successfully.
De-configuring Listener configuration file...
Listener configuration file de-configured successfully.
De-configuring Local Net Service Names configuration file...
Local Net Service Names configuration file de-configured successfully.
De-configuring backup files...
Backup files de-configured successfully.
The network configuration has been cleaned up successfully.
Network Configuration clean config END
Oracle Configuration Manager clean START
OCM clean log file location : /tmp/deinstall2012-04-19_01-29-47AM/logs//ocm_clean1221.log
Oracle Configuration Manager clean END
Setting the force flag to false
Setting the force flag to cleanup the Oracle Base
Oracle Universal Installer clean START
Detach Oracle home '/orcl/oracle/product/11.2.0.3' from the central inventory on the local node : Done
Delete directory '/orcl/oracle/product/11.2.0.3' on the local node : Done
Delete directory '/orcl/oracle/oraInventory' on the local node : Done
The Oracle Base directory '/orcl/oracle' will not be removed on local node. The directory is not empty.
Oracle Universal Installer cleanup was successful.
Oracle Universal Installer clean END
## [START] Oracle install clean ##
Clean install operation removing temporary directory '/tmp/deinstall2012-04-19_01-29-47AM' on node 'node1'
## [END] Oracle install clean ##
######################### CLEAN OPERATION END #########################
####################### CLEAN OPERATION SUMMARY #######################
Successfully de-configured the following database instances : orcl
Following Single Instance listener(s) were de-configured successfully: LISTENER_orcl
Cleaning the config for CCR
Cleaning the CCR configuration by executing its binaries
CCR clean is finished
Successfully detached Oracle home '/orcl/oracle/product/11.2.0.3' from the central inventory on the local node.
Successfully deleted directory '/orcl/oracle/product/11.2.0.3' on the local node.
Successfully deleted directory '/orcl/oracle/oraInventory' on the local node.
Oracle Universal Installer cleanup was successful.
Run 'rm -rf /etc/oraInst.loc' as root on node(s) 'node1' at the end of the session.
Run 'rm -rf /opt/ORCLfmap' as root on node(s) 'node1' at the end of the session.
Oracle deinstall tool successfully cleaned up temporary directories.
#######################################################################
############# ORACLE DEINSTALL & DECONFIG TOOL END #############

How to uninstall Oracle database 11g

This note apply to linux version and Oracle Database RAC or Standalone.
 1. First of all uninstall the database and after grid:
To uninstall the database run as oracle user :
$ORACLE_HOME/deinstall/deinstall
This script will require at the end of process, to run other script as root user.
 2. After uninstall the database uninstall the grid:
To uninstall the grid infrastructure, run as oracle user :
$ORACLE_HOME/deinstall/deinstall
This script will require at the end of process, to run other script as root user.
 3. Remove trash’s :
3.1  TMP:
rm -rf /tmp/*
3.2 Oracle Base
cd $ORACLE_BASE
rm -rf *
3.3 ETC
rm -rf /etc/ora*
Good Luck !

Tuesday, February 18, 2014

[PostgreSQL/PPAS] Ora2Pg - Migrates Oracle Databases to PostgreSQL



1. 下載所需檔案
    a.Oracle:下載OCI 的base及sdk(這裡)
    b.Perl:下載DBD:Oracle(這裡)
    c.Ora2Pg:下載ora2pg source (這裡)

2. 安裝OCI
    # rpm -Uvh oracle-instantclient12.1-basic-12.1.0.1.0-1.x86_64.rpm
    # rpm -Uvh oracle-instantclient12.1-devel-12.1.0.1.0-1.x86_64.rpm
    # vi /etc/ld.so.conf.d/oci.conf
============oci.conf start================
/usr/lib/oracle/12.1/client64/lib
============oci.conf  EOF================
    # ldconfig -v

3. 安裝Perl DBD:Oracle模組
   # tar -zxvf DBD-Oracle-1.68.tar.gz
   # cd DBD-Oracle-1.6
   # export ORACLE_HOME=/usr/lib/oracle/12.1/client64
   # export PATH=$PATH:$ORACLE_HOME/bin
   # export LD_LIBRARY_PATH=$ORACLE_HOME/lib
   # perl Makefile.PL -V 12.1.0
   # make install

4. 安裝Ora2Pg
   # tar -jxvf ora2pg-12.0.tar.bz2
   # cd ora2pg-12.0
   # perl Makefile.PL
   # make && make install

5. Ora2Pg組態 

Tuesday, February 11, 2014

ETL : Moving Data From Oracle To PostgreSQL

  • Installing and configuring oracle instant client x86_64
  • Installing perl-DBD-Oracle
  • Installing and configuring ora2pg 
 
  1. Install and Configure Oracle Instant Client for linux
  2. I'm going to cover this step in quite a bit of detail; even though there are pre-built .rpm packages available from oracle for both i386 and x86_64 platforms, getting everything in running can be quite a mission if you omit a few vital steps...
    1. Download the Oracle Instant Client .rpm's from Oracle here
      Make sure you get the following :
      • oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
      • oracle-instantclient11.2-sqlplus-11.2.0.3.0-1.x86_64.rpm
      • oracle-instantclient11.2-devel-11.2.0.3.0-1.x86_64.rpm

    2. Once you've downloaded the .rpm's, you can install them either with rpm or yum (I generally prefer yum as it will automatically handle resolving and installing dependencies for you).

      $ sudo yum -y localinstall oracle-instantclient*.rpm
    3. Update the ld library cache

    4. $ cat > /etc/ld.so.conf.d/oracle.conf <<EOF
      /usr/lib/oracle/11.2/client64/lib
      EOF

      $ ldconfig

    5. Set the Oracle environment variable

      $ cat >> /etc/bashrc <<EOF
      export TNS_ADMIN=$HOME
      export EDITOR=vim
      export ORACLE_HOME=/usr/lib/oracle/11.2/client64
      EOF

      $ source /etc/bashrc

    6. Place your tnsnames.ora file in your home directory
    7. You can test your oracle client installation by running sqlplus

      $ sqlplus64 /nolog
  3. Install Perl-DBD-Oracle

    1. Before we start ensure that you have the following packages installed
      • perl
      • perl-CPAN
      • perl-DBD
      • perl-DBI
      • gcc
      • libaio
      • libaio-devel

    2. Download the Perl-DBD-Oracle Source with CPAN


    $ perl -MCPAN -e shell
    CPAN> get DBD::Oracle
    CPAN> exit

    $ cd ~/.cpan/build/DBD-Oracle*
    $ perl Makefile.PL
    $ make
    $ make install

  4. Install and Configure ora2pg

    1. Download ora2pg here
    2. Uncompress the tar archive

      $ tar xjvf ora2pg*.tar.bz2 && rm ora2pg*.tar.bz2
    3. Build ora2pg

    4. $ cd ora2pg*
      $ perl Makefile.PL
      $ make && make install

    5. Configure ora2pg

    6. $ gedit /etc/ora2pg/ora2pg.conf
      Look out for the following configuration properties
      • ORACLE_HOME - you can set this to $ORACLE_HOME
      • ORACLE_DSN - set this to the desired entry in you tnsnames.ora
      • ORACLE_USER - the oracle username
      • ORACLE_PWD - the oracle password
      • USER_GRANTS - set this to 1 if you're not connecting as a DBA role
      • TYPE - set this to DATA if you only want to export data and ignore structure
    7. run ora2pg
    8. Simply run ora2pg from the command line, by default your data will be dumped to a file called output.sql in the current directory.

Thursday, February 6, 2014

Oracle DBMS_LOCK


Oracle DBMS_LOCK
Version 11.1
 
General Information
Source {ORACLE_HOME}/rdbms/admin/dbmslock.sql
First Available 7.3.4

Constants
Name Description Data Type Value
nl_mode NuLl INTEGER 1
ss_mode Sub Shared: used on an aggregate object to indicate that share locks are being acquired on subparts of the object INTEGER 2
sx_mode Sub eXclusive: used on an aggregate object to indicate that exclusive locks are being acquired on sub-parts of the object INTEGER 3
s_mode Shared: indicates that the entire aggregate object has a share lock, but some of the sub-parts may additionally have exclusive locks INTEGER 4
ssx_mod Shared SubeXclusive INTEGER 5
x_mode eXclusive INTEGER 6

Dependencies
SELECT referenced_name
FROM dba_dependencies
WHERE name = 'DBMS_LOCK'
UNION
SELECT name
FROM dba_dependencies
WHERE referenced_name = 'DBMS_LOCK';
Exceptions
Error Number Description
ORA-20000
Unable to find or insert lock <lockname> into catalog dbms_lock_allocated.
ORU-10003 Unable to find or insert lock <lockname> into catalog dbms_lock_allocated.
Object Privileges GRANT execute ON dbms_lock TO <schema_name>
GRANT execute ON dbms_lock TO uwclass;
 
ALLOCATE_UNIQUE
Allocates a unique lock identifier (in the range of 1073741824 to 1999999999) given a lock name. Lock identifiers are used to enable applications to coordinate their use of locks dbms_lock.allocate_unique(
lockname        IN  VARCHAR2,
lockhandle      OUT VARCHAR2,
expiration_secs IN  INTEGER DEFAULT 864000);
See dbms_lock demo
 
CONVERT

Converts a lock from one mode to another

Overload 1
dbms_lock.convert(
id       IN INTEGER,
lockmode IN INTEGER,
timeout  IN NUMBER DEFAULT maxwait)
RETURN INTEGER;
Return Values
0 Success
1 Timeout
2 Deadlock
3 Parameter error
4 Don't own lock specified by id or lockhandle
5 Illegal lock handle
See dbms_lock demo

Overload 2
dbms_lock.convert(
lockhandle IN VARCHAR2,
lockmode   IN INTEGER,
timeout    IN NUMBER DEFAULT maxwait)
RETURN INTEGER;
See dbms_lock demo
 
RELEASE

Explicitly releases a lock previously acquired using the REQUEST function

Overload 1
dbms_lock.release(id IN INTEGER) RETURN INTEGER;
Return Values
0 Success
3 Parameter error
4 Don't own lock specified by id or lockhandle
5 Illegal lock handle
See dbms_lock demo
Overload 2 dbms_lock.release(lockhandle IN VARCHAR2) RETURN INTEGER;
See dbms_lock demo
 
REQUEST

Requests a lock with a given mode

Overload 1
dbms_lock.request(
id                IN INTEGER,
lockmode          IN INTEGER DEFAULT x_mode,
timeout           IN INTEGER DEFAULT maxwait,
release_on_commit IN BOOLEAN DEFAULT FALSE)
RETURN INTEGER;
Return Values
0 Success
1 Timeout
2 Deadlock
3 Parameter error
4 Don't own lock specified by id or lockhandle
5 Illegal lock handle
See dbms_lock demo

Overload 2
dbms_lock.request(
lockhandle        IN VARCHAR2,
lockmode          IN INTEGER DEFAULT x_mode,
timeout           IN INTEGER DEFAULT maxwait,
release_on_commit IN BOOLEAN DEFAULT FALSE)
RETURN INTEGER;
See dbms_lock demo
 
SLEEP
Suspends the session for a given period of time dbms_lock.sleep(seconds IN NUMBER);
exec dbms_lock.sleep(1.00);
 
Demo
-- create demo table

CREATE TABLE lock_test (
action VARCHAR2(10),
when   TIMESTAMP(9));

GRANT insert ON lock_test TO public;

CREATE OR REPLACE PACKAGE lock_demo IS
 v_lockname   VARCHAR2(12) := 'control_lock';
 v_lockhandle VARCHAR2(200);
 v_result     PLS_INTEGER;

-- obtain a lock
PROCEDURE request_lock(p_ltype INTEGER, p_retval OUT INTEGER);
-- release an existing lock
PROCEDURE release_lock(p_retval OUT INTEGER);
-- view the stored handle
FUNCTION see_handle RETURN VARCHAR2;
-- decode lock request
FUNCTION decode_req(p_result PLS_INTEGER) RETURN VARCHAR2;
-- decode lock release
FUNCTION decode_rel(p_result PLS_INTEGER) RETURN VARCHAR2;

END lock_demo;
/


CREATE OR REPLACE PACKAGE BODY lock_demo IS

PROCEDURE request_lock(p_ltype IN INTEGER, p_retval OUT INTEGER) IS
BEGIN
  IF v_lockhandle IS NULL THEN
    dbms_lock.allocate_unique(v_lockname, v_lockhandle);
  END IF;
    p_retval := dbms_lock.request(v_lockhandle, p_ltype);
END request_lock;
------------------------------------------------------------
PROCEDURE release_lock(p_retval OUT INTEGER) IS
BEGIN
  IF v_lockhandle IS NOT NULL THEN
    p_retval := dbms_lock.release(v_lockhandle);
  END IF;
END release_lock;
------------------------------------------------------------
FUNCTION see_handle RETURN VARCHAR2 IS
BEGIN
  IF v_lockhandle IS NOT NULL THEN
    RETURN v_lockhandle;
  ELSE
    RETURN 'Not Allocated';
  END IF;
END see_handle;
------------------------------------------------------------
FUNCTION decode_req(p_result PLS_INTEGER) RETURN VARCHAR2 IS
 retval VARCHAR2(20);
BEGIN
  SELECT DECODE(p_result,0,'Success',1,'Timeout',2,'Deadlock',
  3,'Parameter Error',4,'Already owned',5,'Illegal Lock Handle')
  INTO retval
  FROM dual;

  RETURN retval;
END decode_req;
------------------------------------------------------------
FUNCTION decode_rel(p_result PLS_INTEGER) RETURN VARCHAR2 IS
 retval VARCHAR2(20);
BEGIN
  SELECT DECODE(p_result,0,3, 'Parameter Error',4, 'Already owned',
  5, 'Illegal Lock Handle')
  INTO retval
  FROM dual;

  RETURN retval;
END decode_rel;
------------------------------------------------------------
END lock_demo;
/

GRANT execute ON lock_demo TO public;


set serveroutput on

-- get an exclusive lock in the current session (Session 1)
DECLARE
 s VARCHAR2(200);
BEGIN
  lock_demo.request_lock(6, s);
  dbms_output.put_line(s);
END;
/

/* Two session request a shared lock (ss_mode). The shared lock cannot be acquired because  session 1 holds an exclusive lock. Execution will stop on the request until the the exclusive lock is released. */
Session 2 Session 3
set serveroutput on

DECLARE
  s VARCHAR2(200);
BEGIN
  uwclass.lock_demo.request_lock(
  dbms_lock.ss_mode, s);

  dbms_output.put_line(s);

  INSERT INTO uwclass.lock_test
  (action, when)
  VALUES
  ('started', SYSTIMESTAMP);

  dbms_lock.sleep(5);

  INSERT INTO uwclass.lock_test
  (action, when)
  VALUES
  ('ended', SYSTIMESTAMP);
  COMMIT;
END;
/
set serveroutput on

DECLARE
  s VARCHAR2(200);
BEGIN
  uwclass.lock_demo.request_lock(
  dbms_lock.ss_mode, s);

  dbms_output.put_line(s);

  INSERT INTO uwclass.lock_test
  (action, when)
  VALUES
  ('started', SYSTIMESTAMP);

  dbms_lock.sleep(5);

  INSERT INTO uwclass.lock_test
  (action, when)
  VALUES
  ('ended' , SYSTIMESTAMP);
  COMMIT;
END;
/

-- Session 1 releases its lock
DECLARE
  s VARCHAR2(200);
BEGIN
  lock_demo.release_lock(s);
  dbms_output.put_line(s);
END;
/

-- Execution resumes when the exclusive lock is released

SELECT TO_CHAR(when,'dd.mm.yyyy hh24:mi:ss'), action
FROM lock_test
ORDER BY when;

Wednesday, February 5, 2014

Oracle Locking Using DBMS_LOCK

We are using the folling Oracle functions to perform row level locking. These functions are called from our WinForms application using dotConnect for Oracle and Enterprise Library 4.1.

-- internal function to get a lock handle
-- (private for use by REQUEST_LOCK and RELEASE_LOCK)
CREATE OR REPLACE FUNCTION GET_HANDLE (i_lock_name IN VARCHAR2) RETURN VARCHAR2 IS
PRAGMA AUTONOMOUS_TRANSACTION;
v_lock_handle VARCHAR2(128);
BEGIN
DBMS_LOCK.ALLOCATE_UNIQUE (
lockname => i_lock_name,
lockhandle => v_lock_handle,
expiration_secs => 864000); -- 10 days
RETURN v_lock_handle;
END GET_HANDLE;

CREATE OR REPLACE PROCEDURE REQUEST_LOCK (i_lock_name IN VARCHAR2) IS
v_lock_status NUMBER;
BEGIN
v_lock_status := DBMS_LOCK.REQUEST(
lockhandle => GET_HANDLE(i_lock_name),
lockmode => DBMS_LOCK.X_MODE, -- eXclusive
timeout => 0, -- do not wait
release_on_commit => FALSE);
CASE v_lock_status
WHEN 0 THEN NULL;
WHEN 2 THEN RAISE_APPLICATION_ERROR(-20000,'deadlock detected');
WHEN 4 THEN RAISE_APPLICATION_ERROR(-20000,'lock already obtained');
ELSE RAISE_APPLICATION_ERROR(-20000,'request lock failed - ' || TO_CHAR(v_lock_status));
END CASE;
END REQUEST_LOCK;

-- wrapper to release a lock
CREATE OR REPLACE PROCEDURE RELEASE_LOCK (i_lock_name IN VARCHAR2) IS
v_lock_status NUMBER;
BEGIN
v_lock_status := DBMS_LOCK.RELEASE(
lockhandle => GET_HANDLE(i_lock_name));
IF v_lock_status > 0 THEN
RAISE_APPLICATION_ERROR(-20000,'release lock failed - ' || TO_CHAR(v_lock_status));
END IF;
END RELEASE_LOCK;


These are the .Net Fuctions that call the Oracle lock functions mentioned above:

Public Function RequestLock(ByVal lockName As String) As Boolean
Dim isLocked As Boolean = True

Try
Dim db As Database
Dim cmd As DbCommand

db = DatabaseFactory.CreateDatabase()
cmd = db.GetStoredProcCommand("REQUEST_LOCK", lockName)
cmd.Connection = _DatabaseConnection.GetConnection()
db.ExecuteNonQuery(cmd)

Catch ex As Exception
isLocked = False
End Try

Return isLocked
End Function

Public Function ReleaseLock(ByVal lockName As String) As Boolean
Dim isReleased As Boolean = True

Try
Dim db As Database
Dim cmd As DbCommand

db = DatabaseFactory.CreateDatabase()
cmd = db.GetStoredProcCommand("RELEASE_LOCK", lockName)
cmd.Connection = _DatabaseConnection.GetConnection()

db.ExecuteNonQuery(cmd)

Catch ex As Exception
isReleased = False
End Try

Return isReleased
End Function


The problem I am having is creating a lock and having that lock persist. I have tried Direct and OCI modes and used the pooling and non-pooling options in connection string and nothing I try will work for us. The Direct/Pooling options works for a period of time but if we monitor the Oracle sessions the connections that hold the locks are closed. Obviously when the connections are dropping the locks disappear as well.

Sample connect strings we have tried.

providerName="dotConnect for Oracle" />
providerName="dotConnect for Oracle" />
providerName="dotConnect for Oracle" />
providerName="dotConnect for Oracle" />

Tuesday, January 21, 2014

Recover Database until cancel

Problem:
Can someone explain why it is necessary to perform "recover database until cancel" before using "alter database open resetlogs" when you are restoring a cold backup without a backup of the redo log files ?

I perform the following steps, which I thought would be very simple, however I get an error on opening the database.
SHUTDOWN IMMEDIATE

Restore all backup datafiles and controlfiles (OS copy)

STARTUP MOUNT

ALTER DATABASE OPEN RESETLOGS

ORA-01139: RESETLOGS option only valid after an incomplete database recovery
So I tried using: 

RECOVER DATABASE UNTIL CANCEL

ALTER DATABASE OPEN RESETLOGS
And this works, the database is opened and the new redo logs are created.
I got a trace of my controlfile and found the following..

CREATE CONTROLFILE REUSE DATABASE "TEST" NORESETLOGS NOARCHIVEMODE .....
I think it is no NORESETLOGS that is causing the problem as if I re-create the control file with RESETLOGS specified it works fine.

Solution: 
The Oracle documentation notes:

"In cancel-based recovery, recovery proceeds by prompting you with the suggested filenames of archived redo log files. Recovery stops when you specify CANCEL instead of a filename or when all redo has been applied to the datafiles.
Cancel-based recovery is better than change-based or time-based recovery if you want to control which archived log terminates recovery. For example, you may know that you have lost all logs past sequence 1234, so you want to cancel recovery after log 1233 is applied.
You should perform cancel-based media recovery in these stages:
  1. Prepare for recovery by backing up the database and correct any media failures as described in "Preparing for Incomplete Recovery".
  2. Restore backup datafiles as described in "Restoring Datafiles Before Performing Incomplete Recovery". If you have a current control file, then do not restore a backup control file.
  3. Perform media recovery on the restored database backup as described in the following procedure.
To perform cancel-based recovery:
  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

    Note:If you fail to specify the UNTIL clause on the RECOVERcommand, then you will not be able to open the database until a complete recovery is done.

  1. 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.


Note:If you use an Oracle Real Application Clusters configuration, and you are performing incomplete recovery or using a backup control file, then Oracle can only compute the name of the first archived redo log file from the first thread. The first redo log file from the other threads must be supplied by the user. After the first log file in a given thread has been supplied, Oracle can suggest the names of the subsequent log files in this thread.

  1. 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.

  1. 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;"

Monday, January 20, 2014

Solving “ORA-03113: end-of-file on communication channel” while starting up Oracle Database 11g

ORA-03113: end-of-file on communication channel
Case:
While trying to open db 11g on linux machine we encounter the error ORA-03113: end-of-file on communication channel.
Investigation and solution:
Returning back to the alert log file we can see the following lines:
*************************************************************************************
ORA-19815: WARNING: db_recovery_file_dest_size of 5368709120 bytes is 100.00% used, and has 0 remaining bytes available.
************************************************************************
You have following choices to free up space from recovery area:
1. Consider changing RMAN RETENTION POLICY. If you are using Data Guard,
then consider changing RMAN ARCHIVELOG DELETION POLICY.
2. Back up files to tertiary device such as tape using RMAN
BACKUP RECOVERY AREA command.
3. Add disk space and increase db_recovery_file_dest_size parameter to
reflect the new space.
4. Delete unnecessary files using RMAN DELETE command. If an operating
system command was used to delete files, then use RMAN CROSSCHECK and
DELETE EXPIRED commands.
************************************************************************
Errors in file /u01/app/oracle/diag/rdbms/mostprod/mostprod/trace/mostprod_ora_11853.trc:
ORA-19809: limit exceeded for recovery files
ORA-19804: cannot reclaim 42960384 bytes disk space from 5368709120 limit
ARCH: Error 19809 Creating archive log file to ‘/u01/flash_rec_area/MOSTPROD/archivelog/2012_11_21/o1_mf_1_177_%u_.arc’
Errors in file /u01/app/oracle/diag/rdbms/mostprod/mostprod/trace/mostprod_ora_11853.trc:
ORA-16038: log 3 sequence# 177 cannot be archived
ORA-19809: limit exceeded for recovery files
ORA-00312: online log 3 thread 1: ‘/u01/app/oracle/oradata/mostprod/redo03.log’
*************************************************************************************
As you   can see the probles is regarding the archive log area is ran out of space.
To solve this issue:
  1. We can follow any of the given suggestions but what we do in our case is to archive some old archived logs and delete then from the archive log area.
  2. Optionally you may change the archive log retention policy to a suitable period of time.
  3. As we remove the archived log files through the OS command we need to tell the database about what we did that is using rman otherwise the database will still failed to open. So…
SQL> startup                                              — Failed to startup, the same ORA-03113 Error
SQL> startup nomount                          — ORACLE Instance Started
SQL> alter database mount                 — Database altered
SQL> exit
$ cd $ORACLE_HOME/bin
$ ./rman target /
RMAN> crosscheck archivelog all      — Here you will see all the names of archivelogs still exist
RMAN> delete expired archivelog all
RMAN> exit
$ sqlplus / as sysdba
SQL> alter database open                    — Database altered
Regards :)

Monday, December 23, 2013

PostgreSQL WAL vs. Oracle Redo Log

Write-Ahead Logging (WAL) in PostgreSQL and Redo Logs in Oracle have some things in common. Here I want to compare both with respect to database configuration.

WAL and Redo Logs both have the same purpose: to guarantee data integrity the database management system must write changes to some kind of stable storage. But instead of writing data directly to the location where it belongs and from where it will be retrieved later on, records describing the changes (in Oracle sometimes called change vectors) are written to dedicated log files. After the log has been flushed to disk the DBMS has enough information available to recreate the original data changes after a crash. The data eventually will be written to the correct location by an operation called checkpoint. When the checkpoint is completed the log is no longer needed for crash recovery (but it could still be valuable for log based replication or disaster recovery).
The invention of these logs is probably the consequence of plain old rotational disks being the prevailing kind of stable storage for most of the Information Age. The throughput of writing sequentially to a disk is much larger than writing single blocks to different spots on the disk. Therefore it will in general be much faster to write the log with a change description than to write the changed data itself to the database files.
The most visible difference between WAL and redo logs is their configuration. An Oracle DBA has to decide on the number of redo logs (two or more; to simplify things I will ignore mirrored redo logs here) and their size. So the disk space used by the redo logs is fixed and will only change if the DBA modifies the configuration. For PostgreSQL on the other hand the size of a WAL file is always 16 megabytes (unless the server software has been recompiled with a different value). The exact number of WAL files depends on a couple of configuration parameters (checkpoint_completion_target, checkpoint_segments & wal_keep_segments) and the current load profile.
So what does this mean for the database operation? Both DBMS will reuse a log when the contained data is no longer needed for recovery. That implies that the checkpoint for the relevant data blocks must have finished. The log must also have been archived successfully if archiving is enabled.
Oracle can only use the pre-configured logs and will emit warnings or error messages when a log cannot be reused. The message “checkpoint not complete” in the alert log indicates that Oracle has to postpone database changes because switching to the next redo log is not yet possible due to the still running checkpoint. Obviously this reduces the performance of the application. It gets worse when the archiver is unable to archive a log. In this case the error message “ORA-00257: archiver error. Connect internal only, until freed” comes up and the database freezes until the issue is resolved by the DBA.
PostgreSQL on the other hand will start to add more WAL files to the directory pg_xlog when it can not reuse an existing log. This prevents the database from stalling if checkpoints do not finish in time or the archiver process can't keep up with the work. Of course an adequate amount of disk space must be reserved for PostgreSQL to make this possible without failures.
Both DBMS offer parameters to control the frequency of checkpoints. In PostgreSQL the parameter checkpoint_timeout is used to define the maximum time interval between two checkpoints. Oracle has a similar parameter called log_checkpoint_timeout. But nowadays the checkpoint frequency is often automatically adjusted to satisfy the crash recovery time. The parameter fast_start_mttr_target sets the target for the duration of a crash recovery and Oracle triggers checkpoints to achieve that goal. So in this case the configuration of Oracle uses a more business aligned number.
In both systems the amount of changes done also triggers a checkpoint. PostgreSQL has the parameter checkpoint_segments to set the number of segments written to the WAL files before a checkpoint happens. As said above, the segments normally have a size of 16 megabytes. So this gives at least 16 megabytes written to WAL until this type of checkpoint is triggered. For Oracle the parameter log_checkpoint_interval specifies the number of OS blocks (containing 512 bytes on most platforms) between checkpoints. A checkpoint is also triggered by a redo log switch and therefore the amount of changes is also defined by the size of the redo logs. A DBA can create redo logs much smaller than 16 megabytes so this could lead to very frequent checkpoints in Oracle. In this case the DBA will have to increase the size of the redo logs to reduce the frequency of these checkpoints. In PostgreSQL the same can by achieved by increasing the parameter checkpoint_segments.
The first step when looking into checkpoint activity is to write the relevant details to a logfile. PostgreSQL uses the parameter log_checkpoints to write details of every checkpoint into the server log. The log even shows if the checkpoint has been triggered by the timeout (indicated by checkpoint starting: time) or by the amount of changes (indicated by checkpoint starting: xlog). Oracle uses the parameter log_checkpoints_to_alert to write details into the alert log.

Monday, September 23, 2013

How to know export START TIME in Oracle database?


Aim:
To determine export start time which is generally not published in export lofile.

Situation:
Below is sample of export log.

Connected to: Oracle Database 10Enterprise Edition Release 10.2.0.4.0 - 64bit Production
With the Partitioning, OLAP, Data Mininand Real Application Testinoptions
Export done in UTF8 character set and AL16UTF16 NCHAR character set

About to export specified tables via Conventional Path ...
Current user changed to APPLSYS
. . exportintable                       FND_USER       5641 rows exported
Export terminated successfully without warnings.

You can find export finish time by

[oracle@myhost tmp]$ ls -l 1.log
-rw-r--r--   1 oracle   dba          547 Apr  4 16:39 1.log

But how to find old (might be 2 months old) export start time which you require now and don't remember at all.


Solution:
Oracle 10has a nice feature called Active Session History which stores all the data regardinyour old sessions.

By the logfile time stamp you atleast know which day export started and you can guess the start date. In this example my export ended at 4 Apr 2011. Out of which I can determine start date should be 4 only (if export is bigger, it might be 3 Apr)

Use your anticiated date below in the query

select  sid,sample_time,session_type,event,program,action,module from  V$ACTIVE_SESSION_HISTORY where EXTRACT(day FROM sample_time)=&dt and module like '%exp%';

Enter only day(number) when asked, in this case only enter 4 (for our example).

It will list all the sessions which ran export. See the example xls attached.
** Only thinmake sure is all SIDs are same since active session history is watchinsession at a period of time called sample_time so you will find multiple rows in output.
But sort by sample_time and pick the oldest time which is your export start time :)

Who is using temporary tablespace Oracle


The below script will give you the temporary tablespace used by Tablespace.

set pagesize 1000
select a.tablespace_name, trunc(b.allocated)Allocated, trunc(a.free) Free, trunc(b.allocated-a.free) USED,
(100-trunc(((b.allocated-a.free)*100)/b.allocated)) Percentfree from
(select tablespace_name, sum(bytes)/1024/1024 free from sys.dba_free_space group by tablespace_name) a,
(select sum(bytes)/1024/1024 allocated, tablespace_name from dba_data_files group by tablespace_name ) b
where a.tablespace_name = b.tablespace_name
union
select 'Total', trunc( sum(b.allocated)), trunc(sum(a.free)), trunc(sum((b.allocated-a.free))),
00000 from
(select tablespace_name, sum(bytes)/1024/1024 free from sys.dba_free_space group by tablespace_name) a,
(select sum(bytes)/1024/1024 allocated, tablespace_name from dba_data_files group by tablespace_name ) b
where a.tablespace_name = b.tablespace_name
order by 2;


**************Output given below *******************************

TABLESPACE_NAME ALLOCATED FREE USED PERCENTFREE
------------------------------ ---------- ---------- ---------- -----------
USERS 5 1 3 35
EXAMPLE 100 22 77 23
TEST_TS 100 99 0 100
UNDOTBS1 160 136 23 86
SYSAUX 330 10 319 4
SYSTEM 490 4 485 1
Total 1185 275 909 0

7 rows selected.


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

Note :

If you want to connect to a database without tnsnames.ora entry it will workout from 10g onwards.

sqlplus username/pwd@//hostname:1521/sidname

RMAN Incremental Backups to Refresh a Standby Database


You can create an incremental backup of the target database containing changes to the database since the creation of the duplicate or the previous syncrhonization.
You can apply the incremental backup to the standby database.


Note: This technique cannot be used to update a duplicate database.

RMAN enables you to synchronize a standby database with a primary database by creating an incremental backup at the source database that contains all changed blocks since the duplicate was created or last refreshed. You then apply the incremental backup to the standby database, which updates it with all changes.

This capability faciliates the temporary conversion of a physcial standby database into a reporting database, as described in Oracle Data Guard Concepts and Administration.. In particular, this capability makes it possible to reverse the effects of converting the standby into a reporting database.

After the standby database has been used for reporting or testing, Flashback Database can reverse any changes resulting from that work, returning the database to its contents when it was still a standby. An incremental backup created with BACKUP INCREMENTAL... FROM SCN can be used to refresh the standby with changes at the primary since the conversion. and then managed recovery can resume. The effect is to return the reporting database to its role as standby.




Using BACKUP INCREMENTAL... FROM SCN

The incremental backup is created at the source database by means of the BACKUP INCREMENTAL FROM SCN=n form of the BACKUP command. For example:

BACKUP DEVICE TYPE SBT INCREMENTAL FROM SCN 750923 DATABASE;
BACKUP INCREMENTAL FROM SCN 750923 DATABASE;
BACKUP DEVICE TYPE DISK INCREMENTAL FROM SCN 750983 DATABASE
FORMAT '/tmp/incr_standby_%U';


RMAN uses the selected SCN as the basis for this incremental backup. For all files being backed up, RMAN includes all data blocks that were changed at SCNs greater than or equal to the FROM SCN in the incremental backup.



Note:

* RMAN does not consider the incremental backup as part of a backup strategy at the source database. The backup is not suitable for use in a normal RECOVER DATABASE operation at the source database.


*
The backup sets produced by this command are written to ?/dbs by default, even if the flash recovery area or some other backup destination is defined as the default for disk backups.


* You must create this incremental backup on disk for it to be useful. When you move the incremental backup to the standby, you must catalog it at the standby as described in "Step 3: Catalog the Incremental Backup Files at the Standby Database". Backups on tape cannot be cataloged.



Refreshing a Standby Database With INCREMENTAL FROM SCN Backups: Example

This example shows the steps required to update a standby database using incremental backups. The assumption is that you have already activated the standby, performed your tests or other operations at the standby, , and then used Flashback Database to undo the effects of those changes. The task here is to refresh the standby with the latest changes to the primary , so that it can resume its role as a standby database.
Step 1: Create the Incremental Backup

Create the needed incremental backup at the source database, using BACKUP with the INCREMENTAL FROM SCN clause.

Assume that the incremental backup to be used in updating the duplicate database is to be created on disk, with the filenames for backup pieces determined by the format /tmp/incr_for_standby/bkup_%U.

RMAN> BACKUP DEVICE TYPE DISK INCREMENTAL FROM SCN 750983 DATABASE
FORMAT '/tmp/incr_for_standby/bkup_%U';


Step 2: Make the Incremental Backup Accessible at the Standby Database

Make the backup pieces containing the incremental backup available in some directory accessible on the system containing the standby database. For this example, assume that the destination directory is called /standbydisk1/incrback/ and ensure that it contains nothing besides the incremental backups from Step 1.


Step 3: Catalog the Incremental Backup Files at the Standby Database

Use the RMAN CATALOG command to register the backup sets in the RMAN repository at the duplicate. With an RMAN client connected to the standby database and the recovery catalog (if you use one at the standby), mount the standby and run the following command:

RMAN> CATALOG START WITH '/standbydisk1/incrback/';


The backups are now available for use in recovery of the standby.


Step 4: Apply the Incremental Backup to the Standby Database

Use the RMAN RECOVER command with the NOREDO option to apply the incremental backup to the standby database. All changed blocks captured in the incremental backup are updated at the standby database, bringing it up to date with the primary database. With an RMAN client connected to the standby database, run the following command:

RMAN> RECOVER DATABASE NOREDO;


You can now resume managed recovery at the standby. Any redo logs required at the standby with changes since those contained in the incremental are automatically requested from the primary and applied.