Home >Database >Mysql Tutorial >How to Export SQLPLUS Query Results to a CSV File?
*Exporting SQLPlus Query Results to CSV**
Problem: How do I export SQL*Plus query results directly into a CSV file?
Solution:
SQL*Plus offers a straightforward method for spooling query output to a CSV file. Follow these steps:
<code class="language-sql">SET COLSEP ',' -- Set comma as column separator SET PAGESIZE 0 -- Suppress header rows SET TRIMSPOOL ON -- Remove trailing whitespace SET HEADSEP OFF -- Remove header separation (optional) SET LINESIZE X -- Adjust line width (X = sum of column widths) SET NUMW X -- Adjust numeric field width (X = appropriate value to avoid scientific notation) SPOOL myfile.csv -- Specify output file name SELECT table_name, tablespace_name FROM all_tables WHERE owner = 'SYS' AND tablespace_name IS NOT NULL; SPOOL OFF -- Close the spool file</code>
This creates myfile.csv
with comma-separated values, no header rows, and trimmed whitespace. A sample output might look like:
<code>TABLE_PRIVILEGE_MAP,SYSTEM SYSTEM_PRIVILEGE_MAP,SYSTEM STMT_AUDIT_OPTION_MAP,SYSTEM DUAL,SYSTEM ...</code>
For additional cleanup, remove leading whitespace before commas using a command like:
<code class="language-bash"> sed 's/\s\+,/,/g' myfile.csv > myfile_cleaned.csv ``` This creates a new file `myfile_cleaned.csv` with the extra whitespace removed.</code>
The above is the detailed content of How to Export SQLPLUS Query Results to a CSV File?. For more information, please follow other related articles on the PHP Chinese website!