Home > Database > Mysql Tutorial > How to Spool SQL Query Results to a CSV File Using SQLPLUS?

How to Spool SQL Query Results to a CSV File Using SQLPLUS?

DDD
Release: 2025-01-17 20:34:11
Original
561 people have browsed it

How to Spool SQL Query Results to a CSV File Using SQLPLUS?

Export SQL query results to CSV format using SQLPLUS

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template