Question:
How to output SQL query results to CSV file using only SQLPLUS?
Answer:
To export query results to a CSV file in SQLPLUS, follow these steps:
<code class="language-sql">-- 设置列分隔符为逗号 set colsep , -- 抑制标题行 set pagesize 0 -- 删除尾随空格 set trimspool on -- 可选:禁用标题分隔符 set headsep off -- 定义行大小和数字宽度 set linesize X -- 将'X'替换为总列宽 set numw X -- 将'X'替换为所需的数字宽度(避免ID上的科学计数法) -- 将结果输出到目标CSV文件 spool myfile.csv -- 执行您的查询 select table_name, tablespace_name from all_tables where owner = 'SYS' and tablespace_name is not null; -- 停止输出 spool off</code>
Additional notes:
This method leaves some spaces between fields. To avoid this, you can use the following variation:
<code class="language-sql">-- 使用竖线作为列分隔符 set colsep | -- 或者,您可以使用以下方法(可能会在逗号前引入空格) set colsep , set trimspool on sed 's/\s+,/,/' myfile.csv </code>
The above is the detailed content of How to Spool SQL Query Results to a CSV File Using SQLPLUS?. For more information, please follow other related articles on the PHP Chinese website!