Category Archives: Oracle

Load File into Database as Blob

You can find lots of procedure or steps to load file from filesystem to database.
one of the easy method is to make a function.
Sample of function:-
CREATE OR REPLACE FUNCTION FN_FILE_BLOB(V_FILENAME VARCHAR2, V_DIRECTORY VARCHAR2) RETURN BLOB
IS
src_loc BFILE;
dest_loc BLOB:=empty_blob();
BEGIN
SRC_LOC := BFILENAME(V_DIRECTORY, V_FILENAME);
DBMS_LOB.OPEN(src_loc, DBMS_LOB.LOB_READONLY);
DBMS_LOB.CREATETEMPORARY(lob_loc => dest_loc, cache => true , dur => dbms_lob.session);
DBMS_LOB.OPEN(dest_loc, DBMS_LOB.LOB_READWRITE);
DBMS_LOB.LOADFROMFILE(dest_lob => dest_loc, src_lob => src_loc , amount => DBMS_LOB.getLength(src_loc));
DBMS_LOB.CLOSE(src_loc);
DBMS_LOB.CLOSE(dest_loc);
RETURN dest_loc;
EXCEPTION
WHEN Others THEN
Dbms_Output.Put_Line(SQLERRM);
RETURN NULL;
END;
/

Usage: SELECT FN_FILE_BLOB('image1.jpg','DUMP_DIR') FROM DUAL;

Convert Blob into Insert Statment

There are many ways to copy Blob column from one server to Another like,

1. Generate file from blob in source server, and import file into destination server using Tools like SQL developer, TOAD.

2. Using DBLink,
INSERT INTO BLOB_TEST SELECT BLOB_COL1 FROM TEST_BLOB@SOURCEDB;
3.  I have recently discovered, you can make dynamic insert statement and run as normal insert statement in destination server.

Example here: sample_blob

Scripts to make dynamic script can be written as

Set serveroutput on
DECLARE
M BLOB;
n NUMBER:=1;
c blob;
l_limit NUMBER:=4000;
vm RAW(32767);
BEGIN
Dbms_Output.Put_Line('DECLARE
c BLOB;
BEGIN
dbms_lob.createtemporary(c,true);');
SELECT  BLOB_COL INTO M FROM TEST_BLOB;
--Dbms_Output.Put_Line(Length(M));
while (n+l_limit<=length(m)) loop
     vm:=(dbms_lob.substr(M,l_limit,n));
     Dbms_Output.Put_Line('dbms_lob.writeappend(c,'||Length(vm)/2||','''||VM||''');');
     n:=n+l_limit;
END LOOP;
vm:=(dbms_lob.substr(M,length(m)-n+999,n));
Dbms_Output.Put_Line('dbms_lob.writeappend(c,'||Length(vm)/2||','''||VM||''');');
Dbms_Output.Put_Line('INSERT INTO blob_test VALUES (c,9);
END;
/');
END;
/

Download Here

Mail Client in Oracle Database

Yes you can receive Mail and send in Oracle Database and store into Database or manipulate email to do some task.
I m always lazy to do some repetative task In my Work i was always ask to do send status of certain task from Database and send to back to them via mail. for a beginning it is fun. but when the request number is increasing it is getting boring and monotonous. so what i did is i installed Mail client in one the schema in my Database which reads emails. then i scheduled the job which reads subject of emails that has keyword [Status] and followed by Report Name. so the scheduler reads and do query and generate report in clob and sends the output to sender Mail.

Tools to Connect Oracle Database

There is always a great debate and confusion on choosing Client tool to connect Oracle database. People have their own opinion based on their ease and feasibility. With discussion with my friends and other DBAs and my own experience here are the list of tool with their merits and demerits

Client Tool Description
Oracle SQL Developer Oracle own free client tool, very powerful with lots of featured with click option. But I don’t like this because its heavy , hangs/freezes a lot in slow network connection and main this I dislike is, it tries to be oversmart tool, like suggesting code table which makes coding slow and impatient.

Good for Newbies, bad for moderate and expert

Toad Right now my friends are using Toad 11. Great tool with lots and lots of feature. Most of the time you don’t need to write a code single click can do many thing which is good for newbies and bad also cause it will help you to forget the code. Disadvantage is it is not free and cost is high for normal use. And disk and memory consumption is really high and hangs whole toad system without any reason
SQL Tools One of my favorite tool, very very light and doesn’t have many feature like Toad or SQL developer. But still some feature are very handy like object view and list with their reference and reference child. Testing code. i recommend this especially for the Pl/SQL developer . Disadvantages: though its free it has stopped developing further version since 2011 and sometimes it doesn’t support some datatype like BLOB, XMLDATA type
DB Visualizer I like this tool just to view schema diagram, though SQL Developer plugin supports Schema diagram, but DB visualizer gives you extra feature to see schema diagram.

Personally for me SQL Tool and SQL Developer is enough to do all DBA daily task and both of them is 100% free 🙂

Exporting Query Output into File

For reporting purpose you might need to dumps lots of query into file.
yes yes, most of the client tools allows to dump directly into xls, html, xml file which take a transfer bandwith to transfer data from server to client. so for big data this system might not be so worth it.you can find lots of way to dump text into file.  here is one of the way i have been doing since 2 yrs.

create or replace procedure dump_table_to_csv(l_query in varchar2,
p_dir   in varchar2,
p_filename in varchar2,
v_separator     VARCHAR2 DEFAULT ‘|’,
DateFORMAT VARCHAR2 DEFAULT ‘DD-MON-YYYY’ )
AS
l_output        utl_file.file_type;
l_theCursor     integer default dbms_sql.open_cursor;
l_columnValue   varchar2(4000);
l_status        integer;
l_colCnt        number := 0;
l_separator     varchar2(1);
l_descTbl       dbms_sql.desc_tab;
BEGIN
l_output := utl_file.fopen( p_dir, p_filename, ‘w’,’10000′ );

EXECUTE IMMEDIATE ‘ALTER SESSION SET NLS_DATE_FORMAT=”DD-MON-YYYY”’;
dbms_sql.parse(  l_theCursor,  l_query, dbms_sql.native );
dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );

for i in 1 .. l_colCnt loop
utl_file.put( l_output, l_separator ||  l_descTbl(i).col_name );
dbms_sql.define_column( l_theCursor, i, l_columnValue, 4000 );
l_separator := v_separator;
end loop;
utl_file.new_line( l_output );

l_status := dbms_sql.execute(l_theCursor);

while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
l_separator := ”;
for i in 1 .. l_colCnt loop
dbms_sql.column_value( l_theCursor, i, l_columnValue );
utl_file.put( l_output, l_separator || l_columnValue );
l_separator := v_separator;
end loop;
utl_file.new_line( l_output );
end loop;
dbms_sql.close_cursor(l_theCursor);
utl_file.fclose( l_output );
EXCEPTION
WHEN OTHERS THEN
raise;
END;
/

and where first argument is your query which generates the data.
2nd one is name of the directory alias
3rd filename you want to make it.
4th seperator, by which you want to separate data from each other. default is ‘|’
and 5th is Date format, in different country way timeformat is different.

e.g.

exec dump_table_to_csv (‘select * from tabs’, ‘DATA_PUMP_DIR’,’test.txt’,’,’,’YYYY-MM-DD’);

Installing Oracle 11g in RHEL 5


  1. Checking the network setup:
a.       Verify the hostname (Issue command hostname)
b.      Change the current hostname in kernel
sysctl kernel.hostname=NEW_HOSTNAME
2.      Editing Hostname /etc/hosts
                127.0.0.1      localhost.localdomain localhost
      ::1            localhost6.localdomain6 localhost6
      192.168.x.x   fullhostname       hostname
               
3.      All necessary prerequisites will be performed automatically.
If you plan to use the “oracle-rdbms-server-11gR2-preinstall” package to perform all your prerequisite setup, follow the instructions at https://public-yum.oracle.com to setup the yum repository for OL, then perform the following command.
        # cd /etc/yum.repos.d
        # mv Oracle-Base.repo Oracle-Base.repo.disabled
        # wget https://public-yum.oracle.com/public-yum-el5.repo
        # yum list
  # yum install oracle-rdbms-server-11gR2-preinstall
        Or 
        # yum install oracle-validated
4.       Manual Configuration.
4.1   Add the following lines to the /etc/security/limits.conf file:
      oracle              soft    nproc   2047
      oracle              hard    nproc   16384
      oracle              soft    nofile  4096
      oracle              hard    nofile  65536
      oracle              soft    stack   10240
4.2   Edit /etc/selinux/config file and disable SELINUX
                SELINUX=disabled
5         Create the new groups and users:
      groupadd -g 501 oinstall
      groupadd -g 502 dba
      groupadd -g 503 oper
      useradd –u 502 -g oinstall -G dba oracle
      passwd oracle
6         Create the directories in which the Oracle software will be installed:
      mkdir -p /u01/app/oracle
      chown -R oracle.oinstall /u01
7         Login as root and issue the following command:
      xhost +
8         Edit /home/oracle/.bash_profile from oracle user as:
export ORACLE_HOSTNAME=hostname;
export ORACLE_UNQNAME=orclunq;
export ORACLE_BASE=/u01/app/oracle;
export ORACLE_HOME=$ORACLE_BASE/product/11.2.0/db_1;
export ORACLE_SID=orcl;
export PATH==$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:/usr/sbin:$PATH;
export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib;
export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib;
9         Unzip Installer of Oracle Database
                # unzip oracle_Linux-x86-64_1of2.zip
      # unzip oracle_Linux-x86-64_1of2.zip
10     Start the Oracle Universal Installer (OUI) by issuing the following command in the database  directory:
      # ./runInstaller
11     Fix the RPM issues and Kernel Parameters as suggested
12     Follow the GUI generated by OUI to complete the installation according to requirement.
13     Install Only Software, By choosing Setup Wizard.
14     After installation of software create database with command
      # dbca
14.1.1      While setting Memory Parameter, Check off the Automatic Memory Management Check Box and choose Set SGA/PGA with Needs

HostName greater than 32 Character

When your server’s hostname exceeds 32 character, then there might have an issue of creating or Running enterprise Manager repository.
for a solution here are the steps to follow.
got to folder $ORACLE_HOME/sysman/admin/emdrep/sql/core/latest/self_monitor$ cd $ORACLE_HOME/sysman/admin/emdrep/sql/core/latest/self_monitor

backup the sqlfile self_monitor_post_creation.sql to any other name incase you need it.
$ cp self_monitor_post_creation.sql self_monitor_post_creation_bk.sql

and edit word “l_host_name  varchar2(32)” to “l_host_name  varchar2(50)” in 2 places of self_monitor_post_creation.sql file

and recreate the enterprise manager repository
 $ emca -config dbcontrol db -repos recreate