Skip to Main Content
  • Questions
  • Dump a oracle table into multiple csv files

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, krishnendu.

Asked: October 25, 2022 - 5:35 am UTC

Last updated: October 26, 2022 - 4:12 am UTC

Version: 18G

Viewed 10K+ times! This question is

You Asked

Hi,

I have to schedule a store procedure from a dbms_scheduler. The table name will be passed as an input parameter to the SP.
Based on the input table name, the column names with data need to dump into multiple .csv files. Suppose the table has 1M records and the requirement is each .csv will have at max 100000 records. So, we should have 10 .csv files when we will execute this SP or it gets executed through dbms_scheduler. Can you pls give some hints in this regard?

and Connor said...

Something like this should get you going

SQL> declare
  2    f utl_file.file_type;
  3    l_rows int := 0;
  4    l_suffix int := 0;
  5  begin
  6    for i in ( select * from emp )
  7    loop
  8      if mod(l_rows,5) = 0 then
  9        utl_file.fclose_all;
 10        l_suffix := l_suffix + 1;
 11        f := utl_file.fopen( 'TEMP', 'file'||l_suffix||'.csv', 'w' );
 12        l_rows := 0;
 13      end if;
 14      l_rows := l_rows + 1;
 15      utl_file.put_line(f,i.empno||','||i.ename);
 16    end loop;
 17    utl_file.fclose_all;
 18  end;
 19  /

PL/SQL procedure successfully completed.

SQL>
SQL>
SQL> host dir x:\temp\file*.csv
 Volume in drive X is SSD
 Volume Serial Number is 3E16-F9D0

 Directory of x:\temp

26/10/2022  12:11 PM                60 file1.csv
26/10/2022  12:11 PM                60 file2.csv
26/10/2022  12:11 PM                59 file3.csv
               3 File(s)            179 bytes
               0 Dir(s)  101,855,199,232 bytes free

SQL> host cat x:\temp\file1.csv
7369,SMITH
7499,ALLEN
7521,WARD
7566,JONES
7654,MARTIN


Is this answer out of date? If it is, please let us know via a Comment

More to Explore

PL/SQL demos

Check out more PL/SQL tutorials on our LiveSQL tool.

PL/SQL docs

PL/SQL reference manual from the Oracle documentation library