9

I was wondering how to go about exporting a query from PL/SQL to an text file or csv file. The query I have in mind exports a huge amount of data (about 1 gig). So I'd also like the data split across multiple files;

out1.csv out2.csv out3.csv

I'd like to be able to decide how many files to split it across.

Anyone have any idea how to do this?

2 Answers 2

8

Use UTL_FILE.

A well known ( probably the most complete discussion on this topic ) discussion on this can be found at Ask Tom, Here , note that many of the examples there date back to oracle 8, so there may be better ways to do it in your version of Oracle.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm that familiar with Oracle and PL/SQL could you please give a litte more detail?
Yep, I was looking for more info, but couldn't find it.. then realised that its UTL_FILE, not DBMS_FILE. I've linked the package spec. Its just a package for reading/writing files to disk
Cool thanks, however I still need to work out how to direct the output to the file and how to perform the spanning.
For the cursor-to-csv part, have a look at www.williamrobertson.net/documents/refcursor-to-csv.shtml
0

Try this

For creating MYDIR

create or replace directory MYDIR as 'F:/DATA/';

Grant all permission to MYDIR via SYS user execute this procedure

 CREATE OR REPLACE PROCEDURE export_to_csv(refcur out sys_refcursor) IS
      v_file   UTL_FILE.file_type;
      v_string VARCHAR2(4000);
      CURSOR c_emp IS
        SELECT ROLE_ID, ROLE_DESC FROM role_mst;
    BEGIN
      open refcur for
        SELECT ROLE_ID, ROLE_DESC FROM role_mst;
      v_file := UTL_FILE.fopen('MYDIR', 'empdata.csv', 'w', 1000);       
      -- if you do not want heading then remove below two lines
      v_string := 'Emp Code, Emp Name';
      UTL_FILE.put_line(v_file, v_string);
      FOR cur IN c_emp LOOP
        v_string := cur.ROLE_ID || ',' || cur.ROLE_DESC;
        UTL_FILE.put_line(v_file, v_string);
      END LOOP;
      UTL_FILE.fclose(v_file);
    EXCEPTION
      WHEN OTHERS THEN
        dbms_output.put_line(sqlerrm);
        IF UTL_FILE.is_open(v_file) THEN
          UTL_FILE.fclose(v_file);
        END IF;
    END;

1 Comment

How does this take into account commas within the field?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.