How do I spool to a CSV formatted file using SQLPLUS?

后端 未结 16 967
执笔经年
执笔经年 2020-11-22 15:40

I want to extract some queries to a CSV output format. Unfortunately, I can\'t use any fancy SQL client or any language to do it. I must use SQLPLUS.

How do I do it?

16条回答
  •  逝去的感伤
    2020-11-22 16:28

    You should be aware that values of fields could contain commas and quotation characters, so some of the suggested answers would not work, as the CSV output file would not be correct. To replace quotation characters in a field, and replace it with the double quotation character, you can use the REPLACE function that oracle provides, to change a single quote to double quote.

    set echo off
    set heading off
    set feedback off
    set linesize 1024   -- or some other value, big enough
    set pagesize 50000
    set verify off
    set trimspool on
    
    spool output.csv
    select trim(
           '"'   || replace(col1, '"', '""') || 
           '","' || replace(col2, '"', '""') ||
           '","' || replace(coln, '"', '""') || '"' ) -- etc. for all the columns
    from   yourtable
    /
    spool off
    

    Or, if you want the single quote character for the fields:

    set echo off
    set heading off
    set feedback off
    set linesize 1024   -- or some other value, big enough
    set pagesize 50000
    set verify off
    set trimspool on
    
    spool output.csv
    select trim(
    '"'   || replace(col1, '''', '''''') || 
    '","' || replace(col2, '''', '''''') ||
    '","' || replace(coln, '''', '''''') || '"' ) -- etc. for all the columns
    from   yourtable
    /
    spool off
    

提交回复
热议问题