简体   繁体   中英

Export PLSQL Variable into CSV file

I have a PL/SQL block in which I declare and populate some variables. I just check the value using eg DBMS_OUTPUT.PUT_LINE('My Name= ' || V_NAME);

I have 42 variables like this and I need to export each variable into a CSV file.

SET SERVEROUTPUT ON;

DECLARE
    RECORD_NUM   VARCHAR2 (10) := 'ITEM0001';
    USER_ID      NUMBER (11);
    FIRST_NAME   VARCHAR2 (25);
    LAST_NAME    VARCHAR2 (25);
BEGIN
    SELECT ID, FIRSTNAME, LASTNAME
      INTO USER_ID, FIRST_NAME, LAST_NAME
      FROM MYSCHEM.EMPLOYEES
     WHERE HIRE_DATE > SYSDATE;

    DBMS_OUTPUT.PUT_LINE ('FIRSTNAME= ' || FIRSTNAME);
    DBMS_OUTPUT.PUT_LINE ('LASTNAME = ' || LAST_NAME);
    DBMS_OUTPUT.PUT_LINE ('USER_ID = ' || USER_ID);
END;
/

How can I export these variables to a CSV file?

Here a minimal example how to use utl_file:

DECLARE
    outputfile   UTL_FILE.file_type;
BEGIN
    outputfile := UTL_FILE.FOPEN ('DIRECTORY', 'filename.csv', 'w');

    UTL_FILE.PUT_LINE (outputfile, 'One,Two,Three');
    UTL_FILE.PUT_LINE (outputfile, '1,2,3');
    UTL_FILE.PUT_LINE (outputfile, '1,2,3');

    UTL_FILE.FCLOSE (outputfile);
END;

Like William mentioned: this will create a file on you database-server.

If you want to create it on the client we need more detials, how your client accesses the db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM