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

后端 未结 16 1129
执笔经年
执笔经年 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:43

    There is a problem using sqlplus to create csv files. If you want the column headers only once in the output and there are thousands or millions of rows, you cannot set pagesize large enough not to get a repeat. The solution is to start with pagesize = 50 and parse out the headers, then issue the select again with pagesize = 0 to get the data. See bash script below:

    #!/bin/bash
    FOLDER="csvdata_mydb"
    CONN="192.168.100.11:1521/mydb0023.world"
    CNT=0376
    ORD="0376"
    TABLE="MY_ATTACHMENTS"
    
    sqlplus -L logn/pswd@//${CONN}</dev/null
    set pagesize 50;
    set verify off;
    set feedback off;
    set long 99999;
    set linesize 32767;
    set trimspool on;
    col object_ddl format A32000;
    set colsep ,;
    set underline off;
    set headsep off;
    spool ${ORD}${TABLE}.tmp;
    select * from tblspc.${TABLE} where rownum < 2;
    EOF
    LINES=`wc -l ${ORD}${TABLE}.tmp | cut -f1 -d" "`
    [ ${LINES} -le 3 ] && {
      echo "No Data Found in ${TABLE}."
    }
    [ ${LINES} -gt 3 ] && {
      cat ${ORD}${TABLE}.tmp | sed -e 's/ * / /g' -e 's/^ //' -e 's/ ,/,/g' -e 's/, /,/g' | tail -n +3 | head -n 1 > ./${ORD}${TABLE}.headers
    }
    
    sqlplus -L logn/pswd@//${CONN}</dev/null
    set pagesize 0;
    set verify off;
    set feedback off;
    set long 99999;
    set linesize 32767;
    set trimspool on;
    col object_ddl format A32000;
    set colsep ,;
    set underline off;
    set headsep off;
    spool ${ORD}${TABLE}.tmp;
    select * from tblspc.${TABLE};
    EOF
    LINES=`wc -l ${ORD}${TABLE}.tmp | cut -f1 -d" "`
    [ ${LINES} -le 3 ] && {
      echo "No Data Found in ${TABLE}."
    }
    [ ${LINES} -gt 3 ] && {
      cat ${ORD}${TABLE}.headers > ${FOLDER}/${ORD}${TABLE}.csv
      cat ${ORD}${TABLE}.tmp | sed -e 's/ * / /g' -e 's/^ //' -e 's/ ,/,/g' -e 's/, /,/g' | tail -n +2 | head -n -1 >> ${FOLDER}/${ORD}${TABLE}.csv
    }
    

提交回复
热议问题