在 sqlplus 中使用假脱机创建 headers 时遇到问题

trouble creating headers using spool in sqlplus

我有很多数据要假脱机到 csv 文件。我需要 set heading off 这样标题就不会重复每一页。但是,我仍然需要我生成的文件包含 headers。有没有办法在查询中添加一行 header(而不是 table 本身),而在假脱机时实际上不会将其视为 header?这是我的有效代码,当我 set heading off.

时它不包含 headers
 select a.col1 as name1, 
        a.col2 as name2, 
        b.col3 as name3
from tab1 a, 
     tab2 b

提前致谢

你想试试:

set pages <number of rows you expect>

例如

set pages 1000

另一种方法可以是像这样的 UNION:

SELECT 'name1', 'name2', 'name3' FROM DUAL UNION select a.col1 as name1, a.col2 as name2, b.col3 as name3 from tab1 a, tab2 b

你总是可以尝试这样的事情:

set heading off;

select 'NAME1' name1, 'NAME2' name2, 'NAME3' name3 from dual
union all
select a.col1 as name1, a.col2 as name2, b.col3 as name3
from tab1 a, tab2 b
where <join condition>;

预计到达时间:如果主查询返回的列类型不全是字符串,则必须显式转换它们。这是一个例子:

create table test1 (col1 number,
                    col2 date,
                    col3 varchar2(10),
                    col4 clob);

insert into test1 values (1, sysdate, 'hello', 'hello');

commit;

select 'col1' col1, 'col2' col2, 'col3' col3, 'col4' col4 from dual
union all
select col1, col2, col3, col4
from   test1;
       *
Error at line 1
ORA-01790: expression must have same datatype as corresponding expression

set heading off;

select 'col1' col1, 'col2' col2, 'col3' col3, to_clob('col4') col4 from dual
union all
select to_char(col1), to_char(col2, 'dd/mm/yyyy hh24:mi:ss'), col3, col4
from   test1;

col1                                     col2                col3       col4    
1                                        05/08/2015 11:23:15 hello      hello   

你说你正在假脱机到一个 CSV 文件,所以列间距可能无关紧要(而且你已经 set colsep ,)。

如果是这样,您可以使用 the SQL*Plus prompt command 伪造一个 header,而不需要联合:

prompt name1,name2,name3

 select a.col1, 
        a.col2, 
        b.col3
from tab1 a, 
     tab2 b

或者一个单独的查询,同样没有联合:

set feedback off
 select 'name1', 'name2', 'name3' from dual;
set feedback on -- optionally; probably not in this case

 select a.col1, 
        a.col2, 
        b.col3
from tab1 a, 
     tab2 b

同样,这些值不会与真实数据列对齐,但对于 CSV,您并不真正关心。 (对于 CSV,我通常会明确地将值与逗号连接起来,这样可以消除大量空白并使文件更小)。