Press "Enter" to skip to content

Import CSV File in Oracle Table Using Stored Procedure

CSV file is a comma delimited file in which fields are separated by the comma. In this article, I am giving an example to import CSV file into oracle table using stored procedure. The stored procedure in Oracle is a PL/SQL program unit which can be a stand-alone or in database package.

You must have a directory object in Oracle database referring to server path in which the file is stored. In the below example I am using directory object name as CSV_DIR and procedure name is read_csv. Also created a function GetString in the procedure read_csv to get the delimited string one by one.

Loading CSV File into Oracle Table using PL/SQL Procedure

CREATE OR REPLACE PROCEDURE read_csv
IS
l_file_type UTL_FILE.file_type;

l_string VARCHAR2 (32765);

TYPE Fieldvalue IS TABLE OF VARCHAR2 (4000)
INDEX BY BINARY_INTEGER;

t_field Fieldvalue;

FUNCTION GetString (Source_string IN VARCHAR2,
Field_position IN NUMBER,
UnTerminated IN BOOLEAN DEFAULT FALSE,
Delimiter IN VARCHAR2 DEFAULT ',')
RETURN VARCHAR2
IS
iPtrEnd PLS_INTEGER := 0;
iPtrStart PLS_INTEGER := 0;
vcSourceStrCopy VARCHAR2 (4000) := Source_string;
BEGIN
IF UnTerminated
THEN
vcSourceStrCopy := vcSourceStrCopy || Delimiter;
END IF;

IF Field_Position > 1
THEN
iPtrStart :=
INSTR (vcSourceStrCopy,
Delimiter,
1,
Field_Position - 1)
+ LENGTH (Delimiter);
ELSE
iPtrStart := 1;
END IF;

iPtrEnd :=
INSTR (vcSourceStrCopy,
Delimiter,
1,
Field_Position);
RETURN SUBSTR (vcSourceStrCopy, iPtrStart, (iPtrEnd - iPtrStart));
END GetString;
BEGIN
l_file_type := UTL_FILE.Fopen ('CSV_DIR', 'abc.csv', 'r');

LOOP
UTL_FILE.Get_Line (l_file_type, l_string);

l_string := l_string || ',';

FOR n IN 1 .. REGEXP_COUNT (l_string, ',')
LOOP
t_field (n) :=
Getstring (l_string,
n,
FALSE,
',');

END LOOP;

INSERT INTO EMP (EMPNO,
ENAME,
JOB,
MGR,
HIREDATE,
SAL,
COMM,
DEPTNO)
VALUES (t_field (1),
t_field (2),
t_field (3),
t_field (4),
TO_DATE (t_field (5), 'dd/mm/yyyy'),
t_field (6),
t_field (7),
t_field (8));
END LOOP;

UTL_FILE.Fclose (l_file_type);

COMMIT;
EXCEPTION
WHEN OTHERS
THEN
IF UTL_FILE.is_open (l_file_type)
THEN
UTL_FILE.Fclose (l_file_type);
END IF;
END;

Please note that you must study your CSV file to map target table correctly. Also handle the date format for date fields, as per your CSV date data format.

import csv file in oracle table