March 10, 2014

Linux FTP Upload from Oracle database.

How can we FTP file transfer from oracle database.
Simple FTP file transfer method in linux. Following script is saved as executable 
which will then be executed by oracle Job. 


#!/bin/bash
HOST='192.168.5.23'; -- FTP Host
USER='oracle';       -- FTP User
PASS='oracle_pass';   -- Password
FDIR='Oracle'; -- Directory
ftp -niv <<EOF_SCRIPT
open $HOST
user $USER $PASS
pwd
lcd /home/oracle/dummy
cd /Oracle/dummy
mput *.*
quit
EOF_SCRIPT
echo -e "FTP transfer complete! \n"


/* I am saving this script as success_file_upload1.sh and created a job 'TEST' 
 for executing the sh file for FTP uploading . */



exec dbms_scheduler.drop_job('TEST');

BEGIN
dbms_scheduler.create_job(
job_name => 'TEST',
job_type => 'executable',
job_action => '/home/oracle/success_file_upload1.sh',
start_date => systimestamp at time zone 'Asia/Calcutta',
job_class => 'DEFAULT_JOB_CLASS',
auto_drop => FALSE,
enabled => TRUE);
END;
/


exec dbms_scheduler.run_job('TEST');


-- Check dba_scheduler_job_run_details view for the details


-- I got this error,
-- ORA-27369: job of type EXECUTABLE failed with exit code: Permission denied

-- I changed ownership for the following file and executed the Job again. 

chown oracle:dba $ORACLE_HOME/bin/extjob


exec dbms_scheduler.run_job('TEST');

ORA-27369: job of type EXECUTABLE failed with exit code: 274662


-- listed the file
ls -ltr extjob

-rwsrwxr-x 1 root dba /sdb1/app/oracle/product/12.1.0/db_1/bin/extjob

-- Then I have edited the file. Job is not created in SYS schema so we need to add the credentials to following file. 

vi $ORACLE_HOME/rdbms/admin/externaljob.ora

run_user = oracle
run_group = dba

-- Now we can Success fully uploaded through FTP. 


to remote location
------------------

ORA-27369: job of type EXECUTABLE failed with exit code: Operation not permitted

Configure SSH / SCP Without Password in Linux
or check the file is already installed.

Then will be success. 

March 7, 2014

Helpfull DBA Scripts.

ORA-00942: table or view does not exist 

Table or view does not exists for V$Session when used PLSQL .

grant privilege to user 


 GRANT SELECT ON V_$SESSION TO User_name;




TO FIND PRIMARY KEY CONSTRAINT AND ITS FOREIGN KEY RELATION WITH COLUMN NAMES
===========================================================================

SELECT a.table_name,
       a.constraint_name pk,
       c.column_name pk_column,
       b.table_name,
       b.constraint_name fk,
       d.column_name fk_column
  FROM user_constraints a
       JOIN user_constraints b
          ON a.constraint_name = b.R_CONSTRAINT_NAME
       JOIN user_cons_columns c
          ON a.constraint_name = c.constraint_name
       JOIN user_cons_columns d
          ON b.constraint_name = d.constraint_name

          order by a.table_name;





TABLESPACE SPACE UTILIZATION STATUS REPORT
=====================================

SET pagesize 300
SET lines 132 pages 66 feedback off
COLUMN tablespace_name        format a15             heading 'Tablespace|(TBS)|Name'
COLUMN autoextensible         format a6              heading 'Can|Auto|Extend'
COLUMN files_in_tablespace    format 999             heading 'Files|In|TBS'
COLUMN total_tablespace_space format 99,999,999,999 heading 'Total|Current|TBS|Space'
COLUMN total_used_space       format 99,999,999,999 heading 'Total|Current|Used|Space'
COLUMN total_tablespace_free_space format 99,999,999,999 heading 'Total|Current|Free|Space'
COLUMN total_used_pct              format 999.99      heading 'Total|Current|Used|PCT'
COLUMN total_free_pct              format 999.99      heading 'Total|Current|Free|PCT'
COLUMN max_size_of_tablespace      format 99,999,999,999 heading 'TBS|Max|Size'
COLUMN total_auto_used_pct         format 999.99      heading 'Total|Max|Used|PCT'
COLUMN total_auto_free_pct         format 999.99      heading 'Total|Max|Free|PCT'

TTITLE left _date center Tablespace Space Utilization Status Report skip 2

WITH tbs_auto AS
     (SELECT DISTINCT tablespace_name, autoextensible
                 FROM dba_data_files
                WHERE autoextensible = 'YES'),
     files AS
     (SELECT   tablespace_name, COUNT (*) tbs_files,
               SUM (BYTES) total_tbs_bytes
          FROM dba_data_files
      GROUP BY tablespace_name),
     fragments AS
     (SELECT   tablespace_name, COUNT (*) tbs_fragments,
               SUM (BYTES) total_tbs_free_bytes,
               MAX (BYTES) max_free_chunk_bytes
          FROM dba_free_space
      GROUP BY tablespace_name),
     AUTOEXTEND AS
     (SELECT   tablespace_name, SUM (size_to_grow) total_growth_tbs
          FROM (SELECT   tablespace_name, SUM (maxbytes) size_to_grow
                    FROM dba_data_files
                   WHERE autoextensible = 'YES'
                GROUP BY tablespace_name
                UNION
                SELECT   tablespace_name, SUM (BYTES) size_to_grow
                    FROM dba_data_files
                   WHERE autoextensible = 'NO'
                GROUP BY tablespace_name)
      GROUP BY tablespace_name)
SELECT a.tablespace_name,
       CASE tbs_auto.autoextensible
          WHEN 'YES'
             THEN 'YES'
          ELSE 'NO'
       END AS autoextensible,
       files.tbs_files files_in_tablespace,
       files.total_tbs_bytes total_tablespace_space,
       (files.total_tbs_bytes - fragments.total_tbs_free_bytes
       ) total_used_space,
       fragments.total_tbs_free_bytes total_tablespace_free_space,
       (  (  (files.total_tbs_bytes - fragments.total_tbs_free_bytes)
           / files.total_tbs_bytes
          )
        * 100
       ) total_used_pct,
       ((fragments.total_tbs_free_bytes / files.total_tbs_bytes) * 100
       ) total_free_pct,
       AUTOEXTEND.total_growth_tbs max_size_of_tablespace,
       (  (  (  AUTOEXTEND.total_growth_tbs
              - (AUTOEXTEND.total_growth_tbs - fragments.total_tbs_free_bytes
                )
             )
           / AUTOEXTEND.total_growth_tbs
          )
        * 100
       ) total_auto_used_pct,
       (  (  (AUTOEXTEND.total_growth_tbs - fragments.total_tbs_free_bytes)
           / AUTOEXTEND.total_growth_tbs
          )
        * 100
       ) total_auto_free_pct
  FROM dba_tablespaces a, files, fragments, AUTOEXTEND, tbs_auto
 WHERE a.tablespace_name = files.tablespace_name
   AND a.tablespace_name = fragments.tablespace_name
   AND a.tablespace_name = AUTOEXTEND.tablespace_name
   AND a.tablespace_name = tbs_auto.tablespace_name(+);



Relocating Datafile in a Tablespace
===========================
Procedure to relocate one or more datafile in a tablespace. 
Connect to the database with admin privilege. And have a current backup of database.

1. Check datafile location 
SQL>select tablespace_name,file_name from dba_data_files where  tablespace_name ='USERS';
TABLESPACE_NAME                FILE_NAME
------------------------------ --------------------------------------------------
USERS                                  /u01/app/oracle/oradata/dockdb/USERS01.dbf

2.Change status of tablespace to offline.
SQL>alter tablespace USERS offline normal;

3.Move file using OS command.
[oracle@host161 ~]$ mv /u01/app/oracle/oradata/dockdb/USERS01.dbf /u02/dockdb/datafiles/
[oracle@host161 ~]$ ll /u02/dockdb/datafiles/USERS01.dbf
-rw-r----- 1 oracle oinstall 104865792 Mar 18 05:05 /u02/dockdb/datafiles/USERS01.dbf

4.Change location of datafile in a Tablespace.
SQL>alter tablespace USERS rename datafile '/u01/app/oracle/oradata/dockdb/USERS01.dbf' to   '/u02/dockdb/datafiles/USERS01.dbf';

5.Chenge the status of tablespace back to Online. 
SQL>alter tablespace USERS online;

6.Review the changed location. 
SQL>select tablespace_name,file_name from dba_data_files where  tablespace_name ='USERS';

To Kill session
===========
select 'alter system kill session '''||sid||','||serial#||''' immediate;'||' -- User is '||username||' from '||osuser
 from v$session where username is not null and username<>'SYS' order by osuser;


To  find the Objects and its count grouped by its status.
========================================


SELECT status,object_type ,count(object_type) count
FROM user_objects
GROUP BY object_type,status
UNION ALL
SELECT status,decode(constraint_type, 'R', 'FOREIGN KEY','P', 'PRIMARY KEY','U' , 'UNIQUE KEY','C','CHECK AND NOT NULL')         object_type,count(constraint_type)
FROM user_constraints
GROUP BY constraint_type,status
UNION ALL
SELECT status,'DISABLED TRIGGERS' as object_type,count(status)
FROM user_triggers
WHERE status='DISABLED'
GROUP BY status
order by status,object_type;

For importing [impdp] without Constraint error
==================================
Use following options in IMPDP for avoiding constraint error when appending table data.:

Table_exists_action=append DATA_OPTIONS=skip_constraint_errors

For Shrinking free space from Datafiles
=============================

set verify off
column file_name format a50 word_wrapped
column smallest format 999,990 heading "Smallest|Size|Poss."
column currsize format 999,990 heading "Current|Size"
column savings  format 999,990 heading "Poss.|Savings"
break on report
compute sum of savings on report
column value new_val blksize
select value from v$parameter where name = 'db_block_size';
/
select file_name,
ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) smallest,
ceil( blocks*&&blksize/1024/1024) currsize,
ceil( blocks*&&blksize/1024/1024) -
ceil( (nvl(hwm,1)*&&blksize)/1024/1024 ) savings
from dba_data_files a,
( select file_id, max(block_id+blocks-1) hwm
from dba_extents
group by file_id ) b
where a.file_id = b.file_id(+) order by savings desc
/

For getting Login time of all users in the database.
=====================================

set lines 300
col os_username for a20
col  terminal for a20
col userhost for a30
select a.username,os_username,a.timestamp,a.logoff_time,a.returncode,terminal,userhost
from dba_audit_session a
where (a.username,a.timestamp) in
(select b.username,max(b.timestamp)
from dba_audit_session b
group by b.username)
and a.timestamp<(sysdate-0) ;

Compile , Unlock and Gather Stats of a Schema.
====================================

exec dbms_utility.compile_schema('schema_name');
exec DBMS_STATS.UNLOCK_SCHEMA_STATS ('schema_name');
exec DBMS_STATS.GATHER_SCHEMA_STATS ('schema_name');


To check current SCN.
=================
SELECT dbms_flashback.get_system_change_number as current_scn FROM DUAL;

SELECT current_scn FROM V$DATABASE;

When I execute this query , I got a value like this :

SQL> SELECT current_scn
     FROM V$DATABASE;


CURRENT_SCN
-----------
 1.2807E+13

But Now I got exact value of SCN

SQL> SELECT to_char(current_scn,99999999999999) from V$DATABASE;

TO_CHAR(CURRENT
---------------
 12807210994059


To check Opened Cursor : 

  SELECT COUNT (a.VALUE) Opened_Cursors, s.username
    FROM v$sesstat a, v$statname b, v$session s
   WHERE     a.statistic# = b.statistic#
         AND s.sid = a.sid
         AND b.name = 'opened cursors current'
GROUP BY s.username;


  SELECT COUNT (a.VALUE) Opened_Cursors
    FROM v$sesstat a, v$statname b, v$session s
   WHERE     a.statistic# = b.statistic#
         AND s.sid = a.sid
         AND b.name = 'opened cursors current'


ORDER BY 1;

For scheduling Mail from Oracle database.

Here is one example for configuring mail that running on scheduler. 
The mail will send when some one disable the job.  
* For security reasons, UTL_MAIL is not enabled by default. You must install it by connecting to SYS, then executing the " utlmail.sql " and " prvtmail.plb " scripts in the $ORACLE_HOME/rdbms/admin directory.


create or replace procedure proc1
is
i number;
begin

select max(id) into i from tab1;
if i is null then

i:=0;
insert into tab1 values(i);
else
i:=i+1;
insert into tab1 values(i);
end if;

commit;

end;
/


BEGIN
  DBMS_SCHEDULER.create_job (
    job_name        => 'tab1_ins_job',
    job_type        => 'STORED_PROCEDURE',
    job_action      => 'PROC1',
    start_date      => SYSDATE,
    repeat_interval => 'freq=minutely; interval=1',
    enabled         => TRUE,
    comments        => 'Job is used for testing enable and disable by the app');
END;
/

create or replace procedure manage_proc1(mod1 in number)
is
begin
if mod1 = 1 then
DBMS_SCHEDULER.disable('tab1_ins_job');
EXECUTE IMMEDIATE 'ALTER SESSION SET smtp_out_server = ''192.168.5.222:25''';
  UTL_MAIL.send(sender => 'me@address.com',recipients => 'mail_id@mymail.com',subject => 'Test Mail Job Disabled ',message => 'Job disabled send_mail',mime_type =>'text; charset=us-ascii');
else
DBMS_SCHEDULER.enable('tab1_ins_job');
EXECUTE IMMEDIATE 'ALTER SESSION SET smtp_out_server = ''192.168.5.222:25''';
  UTL_MAIL.send(sender => 'me@address.com',recipients => 'mail_id@mymail.com',subject => 'Test Mail Job Enabled ',message => 'Job Enabled send_mail',mime_type =>'text; charset=us-ascii');
end if;
end;
/


------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- In order to successful execute UTL_MAIL package we need to create Access control list. Please follow the example shown below.

Oracle 11g introduces fine grained access to network services using access control lists (ACL) in the XML DB repository, allowing control over which users access which network resources, regardless of package grants.
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

BEGIN
   DBMS_NETWORK_ACL_ADMIN.create_acl (
      acl           => 'test_acl_file.xml',
      description   => 'A test of the ACL functionality',
      principal     => 'SCOTT', -- principal is the username who execute the mail package
      is_grant      => TRUE,
      privilege     => 'connect',
      start_date    => SYSTIMESTAMP,
      end_date      => NULL);
   COMMIT;
END;
/

BEGIN
   DBMS_NETWORK_ACL_ADMIN.assign_acl (acl          => 'test_acl_file.xml',
                                      HOST         => '192.168.5.222', -- Mail server IP, we can give mail server domain address
                                      lower_port   => 25,      -- And its port
                                      upper_port   => NULL);
   COMMIT;
END;
/

Configure Enterprise Manager For a Database which Copied Manually.




$ emca -config dbcontrol db
.
.
-- if you are manually configuring EM you will end up with following Warning Message.
.
.
Feb 14, 2014 8:25:36 AM oracle.sysman.emcp.EMConfig perform
INFO: This operation is being logged at /u01/app/oracle/cfgtoollogs/emca/dockdb/emca_2014_02_14_08_25_16.log.
.
.

WARNING: Error executing /u01/app/oracle/product/11.2.0/db_1/bin/emctl config emkey -repos
Feb 14, 2014 8:27:24 AM oracle.sysman.emcp.util.DBControlUtil secureDBConsole
WARNING: Configuring EM-Key failed.
Feb 14, 2014 8:27:24 AM oracle.sysman.emcp.EMDBPostConfig performConfiguration
WARNING: Error securing Database control.
Feb 14, 2014 8:27:24 AM oracle.sysman.emcp.EMDBPostConfig setWarnMsg
INFO: Error securing Database Control, Database Control has been brought up in non-secure mode. To secure the Database Control execute the followi            ng command(s):


1) Set the environment variable ORACLE_SID to dockdb
 2) /u01/app/oracle/product/11.2.0/db_1/bin/emctl stop dbconsole
 3) /u01/app/oracle/product/11.2.0/db_1/bin/emctl config emkey -repos -sysman_pwd < Password for SYSMAN user >
 4) /u01/app/oracle/product/11.2.0/db_1/bin/emctl secure dbconsole -sysman_pwd < Password for SYSMAN user >
 5) /u01/app/oracle/product/11.2.0/db_1/bin/emctl start dbconsole

-- You should follow the Steps provided by Oracle .



$ emctl stop dbconsole

$ emctl config emkey -repos -sysman_pwd password

-- On the second step you may get following message. 

The Em Key could not be configured. The Em Key was not found in Management Repository.

$ emctl secure dbconsole -sysman_pwd dbdock

Oracle Enterprise Manager 11g Database Control Release 11.2.0.1.0
Copyright (c) 1996, 2009 Oracle Corporation.  All rights reserved.
http://host161.localdomain:1158/em/console/aboutApplication
DBCONSOLE already stopped...   Done.
Agent is already stopped...   Done.
Securing dbconsole...   Started.
Securing dbconsole...   Failed.
EMKey is misconfigured.             -- Please note this message.


$ emctl start dbconsole

/* So once you identify the Configuration still have issue. Then check status of emkey using following command.

The emkey is an encryption key that is used to encrypt and decrypt sensitive data in Enterprise Manager such as host passwords, database passwords and others. By default, the emkey is stored in the $ORACLE_HOME/sysman/config/emkey.ora file. The location of this file can be changed. */

$ emctl status emkey
Oracle Enterprise Manager 11g Database Control Release 11.2.0.1.0
Copyright (c) 1996, 2009 Oracle Corporation.  All rights reserved.
Please enter repository password:

The Em Key is not configured properly or is corrupted in the file system and does not exist in the Management Repository. To correct the problem:
1) Copy the emkey.ora file from another OMS or backup machine to the OH/sysman/config directory.
2) Configure the emkey.ora file by running "emctl config emkey -emkeyfile <emkey.ora file location>".

-- This time we have to follow these two steps...  


$ emctl config emkey -emkeyfile /u01/emkey.ora
Please enter repository password:

The Em Key is already configured. To override the current configuration, run "emctl config  emkey <options> -force".

$
$ emctl config emkey -emkeyfile /u01/emkey.ora -force
Please enter repository password:

The Em Key has been configured successfully.

-- Now we back to Our Old Four steps. 

$ emctl stop dbconsole
$ emctl config emkey -repos -sysman_pwd dbdock

$ emctl secure dbconsole -sysman_pwd dbdock
.
.
DBCONSOLE already stopped...   Done.
Agent is already stopped...   Done.
Securing dbconsole...   Started.
Securing dbconsole...   Sucessful.

$ emctl start dbconsole
Oracle Enterprise Manager 11g Database Control Release 11.2.0.1.0
Copyright (c) 1996, 2009 Oracle Corporation.  All rights reserved.
https://host161.localdomain:1158/em/console/aboutApplication
Starting Oracle Enterprise Manager 11g Database Control ..... started.
------------------------------------------------------------------
Logs are generated in directory /u01/app/oracle/product/11.2.0/db_1/host161.localdomain_dockdb/sysman/log

-- We should Backup this emkey file. 

June 19, 2013

Cant install package elfutils-libelf-devel-*

Oracle 11g Installation on Oracle Linux 5.9


While installing oracle 11g it may show dependency error at rpm "
elfutils-libelf-devel-* "

rpm -Uvh elfutils-libelf-devel-*

In that case please install both package using following command :
 
rpm -ivh elfutils-libelf-devel-0.137-3.el5.x86_64.rpm elfutils-libelf-devel-static-0.137-3.el5.x86_64.rpm

June 14, 2013

ORA-01262 , ORA-01261

SQL> startup pfile=/u01/app/oracle/product/11.2.0/db_1/dbs/initDB11G.ora

ORA-01261: Parameter db_recovery_file_dest destination string cannot be translated
ORA-01262: Stat failed on a file destination directory
Linux-x86_64 Error: 2: No such file or directory




ORA-01262:

Stat failed on a file destination directory
Cause: Unable to get information about an Oracle managed files destination directory.
Action: Check the permissions on the directory or use a different directory name.


If this error rises when startup database using pfile please verify whether all the path or directory specified in init.ora is exist or not. 

Manually creating Oracle 11g Database





Step 1:Specify an Instance Identifier (SID)
export ORACLE_SID=db11g

Step 2:Ensure That the Required Environment Variables Are Set
$PATH
$ORACLE_HOME
$ORACLE_BASE
   
Step 3:Choose a Database Administrator Authentication Method
  •         With a password file
  •         With operating system authentication
orapwd file=$ORACLE_HOME/dbs/orapwdb11g password=sys

Step 4:Create the Initialization Parameter File
Sample init.ora file will be available in $ORACLE_HOME/dbs. Edit init.ora if needed. 

db_name='db11g'
memory_target=1G
processes = 150
audit_file_dest='$ORACLE_BASE/admin/orcl/adump'
audit_trail ='none'
db_block_size=8192
db_domain=''
db_recovery_file_dest='$ORACLE_BASE/flash_recovery_area'
db_recovery_file_dest_size=2G
diagnostic_dest='$ORACLE_BASE'
dispatchers='(PROTOCOL=TCP) (SERVICE=ORCLXDB)'
open_cursors=300
remote_login_passwordfile='EXCLUSIVE'
undo_tablespace='UNDOTBS1'
# You may want to ensure that control files are created on separate physical
# devices
control_files = (ora_control1, ora_control2)
compatible ='11.2.0'


For convenience, store your initialization parameter file in the Oracle Database default location, using the default file name. Then when you start your database, it will not be necessary to specify the PFILE clause of the STARTUP command, because Oracle Database automatically looks in the default location for the initialization parameter file.

*Default location will be $ORACLE_HOME/dbs
*Default name will be initORACLE_SID.ora

Step 6:Connect to the Instance

sqlplus /nolog

SQL> conn / as sysdba
Connected to an idle instance.

Step 7:Create a Server Parameter File

SQL> create spfile from pfile;
File created.

Step 8: Start the Instance
startup nomount

Step 9: Issue the CREATE DATABASE Statement
 CREATE DATABASE db11g
 USER SYS IDENTIFIED BY sys
 USER SYSTEM IDENTIFIED BY sys
 LOGFILE GROUP 1 ('/u01/app/oracle/oradata/db11g/redo01a.log') SIZE 100M BLOCKSIZE 512,
                  GROUP 2 ('/u01/app/oracle/oradata/db11g/redo02a.log') SIZE 100M BLOCKSIZE 512,
                  GROUP 3 ('/u01/app/oracle/oradata/db11g/redo03a.log') SIZE 100M BLOCKSIZE 512
 MAXLOGFILES 5
 MAXLOGMEMBERS 5
 MAXLOGHISTORY 1
 MAXDATAFILES 100
 CHARACTER SET US7ASCII
 NATIONAL CHARACTER SET AL16UTF16
 EXTENT MANAGEMENT LOCAL
 DATAFILE '/u01/app/oracle/oradata/db11g/system01.dbf' SIZE 325M REUSE
 SYSAUX DATAFILE '/u01/app/oracle/oradata/db11g/sysaux01.dbf' SIZE 325M REUSE
 DEFAULT TABLESPACE users
 DATAFILE '/u01/app/oracle/oradata/db11g/users01.dbf'
 SIZE 500M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED
 DEFAULT TEMPORARY TABLESPACE temp
 TEMPFILE '/u01/app/oracle/oradata/db11g/temp01.dbf'
 SIZE 20M REUSE
 UNDO TABLESPACE undotbs1
 DATAFILE '/u01/app/oracle/oradata/db11g/undotbs01.dbf'
 SIZE 200M REUSE AUTOEXTEND ON MAXSIZE UNLIMITED;


Step 10: Run Scripts to Build Data Dictionary Views

@?/rdbms/admin/catalog.sql
@?/rdbms/admin/catproc.sql
@?/sqlplus/admin/pupbld.sql    -- connect as system to execute this script

'?' will automatically locate $ORACLE_HOME.


More Reference: Oracle 11gR2 Documentation