Home >Database >Mysql Tutorial >How to Export SQLPLUS Query Results to a CSV File?

How to Export SQLPLUS Query Results to a CSV File?

DDD
DDDOriginal
2025-01-17 20:41:10942browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn