SQL*Loader - Load data into table from CSV file
In this article, I am going to show how we can use Oracle SQL *Loader to insert data into the Oracle table. We will create one simple table and create the necessary files required to load the data from the CSV file into the table using Oracle SQL*Loader. The example given in this article is very basic and it will help beginners to understand the SQL*Loader concept. SQL*Loader has various options to load data and support multiple input data formats.
CREATE TABLE EMPLOYEE (
EMPLOYEE_ID NUMBER(8,0),
NAME VARCHAR2(40),
EMAIL VARCHAR2(60) NOT NULL,
DOB DATE,
PRIMARY KEY (EMPLOYEE_ID)
);
The control file is a text file that SQL*Loader uses to understand where to find the data file, how to parse the data and how to insert the data into the oracle table and many other options.
Given below is the sample format of the control file which is used to load the CSV file into the employee table.
-- Employee.ctl file
LOAD DATA
INSERT
INTO TABLE EMPLOYEE
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
TRAILING NULLCOLS
(
EMPLOYEE_ID,
NAME,
EMAIL,
DOB DATA "DD-MON-YYYY"
)
The INSERT option is used for first-time data load and the table should be empty. Otherwise, SQL*Loader will complain and throw an error:
SQL*Loader-601: For INSERT option, table must be empty
If you want to load a CSV file into the table which is not empty then, you can use the APPEND or TRUNCATE option in the control file as given below:
LOAD DATA
APPEND
INTO TABLE EMPLOYEE
.....
.....
APPEND option will add new records in the existing table without deleting any existing records
The TRUNCATE option will truncate the existing table before loading data
Given below a sample CSV file:
1,James, james@gmail.com, 10-OCT-1988
2,Bryan, brayn_rocks@yahoo.com, 12-NOV-1987
3,Scott, scott@rediff.com, 12-MAY-1999
4,Pankaj Bhandari, pankaj@yahoo.com, 12-JUN-1992
5,Suraj Singh, ssing@gmail.com, 13-JUN-2000
Given below a sample script that we can use to run SQL*Loader utility
#!/bin/sh
sqlldr username/password@database control=employee.ctl \
data=employee.dat bad=employee.bad log=employee_load.log
reurntcode=`echo $?`
case "$returncode" in
0) echo "Data loaded successfully";;
1) echo "Execution exited with failures, see logfile" ;;
2) echo "Execution exited with warnings, see logfiles" ;;
3) echo "Fatal Error" ;;
*) echo "Unknown Error" ;;
esac
exit;
You can give a try your hands on SQL*Loader utility and let me know, how it goes for you?
Comments
Post a Comment