Monday 2 December 2013

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 MYDIR as '/home/oracle/file';
Note: /home/oracle/file has to be physical location on disk. 
2)
 grant read, write on directory MYDIR 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('MYDIR','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/file/" location.
 just ope your file and check it 

7369,SMITH,1300,20,RESEARCH
7499,ALLEN,2100,30,SALES
7521,WARD,1200,30,SALES
7566,JONES,3475,20,RESEARCH
7654,MARTIN,1200,30,SALES
7698,BLAKE,3350,30,SALES
7782,CLARK,2950,10,ACCOUNTING
7788,SCOTT,3700,20,RESEARCH
7839,KING,5500,10,ACCOUNTING
7844,TURNER,2000,30,SALES
7876,ADAMS,1600,20,RESEARCH
7900,JAMES,1450,30,SALES
7902,FORD,3500,20,RESEARCH
7934,MILLER,1800,10,ACCOUNTING


NB:-If you want .txt file just change your file format EMP_DEPT.csv to EMP_DEPT.txt.

No comments:

Post a Comment