0% found this document useful (0 votes)
168 views

Create CSV File Using PL-SQL

The document describes how to create a CSV file using PL/SQL. It provides steps to create a directory, grant permissions to it, and write a PL/SQL block that opens a file, runs a cursor to select data from tables, and writes the rows to the CSV file by looping through the cursor and outputting column values separated by commas on each line. Running the procedure will create a CSV file that can then be viewed by changing to the directory and using the cat command on Linux.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views

Create CSV File Using PL-SQL

The document describes how to create a CSV file using PL/SQL. It provides steps to create a directory, grant permissions to it, and write a PL/SQL block that opens a file, runs a cursor to select data from tables, and writes the rows to the CSV file by looping through the cursor and outputting column values separated by commas on each line. Running the procedure will create a CSV file that can then be viewed by changing to the directory and using the cat command on Linux.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Create CSV file using PL/SQL

To create a file, we need to create a directory and have the read write permission as

1) create or replace directory MYCSV as '/home/oracle/mycsv';


Note: /home/oracle/mycsv has to be physical location on disk.
2) grant read, write on directory MYCSV to scott;

Following is the pl/sql sample code to create CSV file

DECLARE
    F UTL_FILE.FILE_TYPE;
    CURSOR C1 IS SELECT EMPNO, ENAME, SAL, E.DEPTNO, DNAME FROM EMP E,
DEPT D WHERE E.DEPTNO = D.DEPTNO ORDER BY EMPNO;
    C1_R C1%ROWTYPE;
BEGIN
    F := UTL_FILE.FOPEN('MYCSV','EMP_DEPT.CSV','w',32767);
    FOR C1_R IN C1
    LOOP
        UTL_FILE.PUT(F,C1_R.EMPNO);
        UTL_FILE.PUT(F,','||C1_R.ENAME);
        UTL_FILE.PUT(F,','||C1_R.SAL);
        UTL_FILE.PUT(F,','||C1_R.DEPTNO);
        UTL_FILE.PUT(F,','||C1_R.DNAME);
        UTL_FILE.NEW_LINE(F);
    END LOOP;
    UTL_FILE.FCLOSE(F);
END;
/

After the execution of above procedure, a file (EMP_DEPT.CSV) would have been created at
"/home/oracle/mycsv/" location.

You may check it on linux by

cd /home/oracle/mycsv
cat EMP_DEPT.CSV

7369,SMITH,800,20,RESEARCH
7499,ALLEN,1600,30,SALES
7521,WARD,1250,30,SALES
7566,JONES,2975,20,RESEARCH
7654,MARTIN,1250,30,SALES
7698,BLAKE,2850,30,SALES
7782,CLARK,2450,10,ACCOUNTING
7788,SCOTT,3000,20,RESEARCH
7839,KING,5000,10,ACCOUNTING
7844,TURNER,1500,30,SALES
7876,ADAMS,1100,20,RESEARCH
7900,JAMES,950,30,SALES
7902,FORD,3000,20,RESEARCH
7934,MILLER,1300,10,ACCOUNTING

Related Post:
- Load CSV file in Oracle using PL/SQL
- Create External Table from CSV File
- Create XML file using PL/SQL
- Load XML file in Oracle Table

You might also like