问题
I have a lot of data that I want to spool to a csv file. I need to set heading off
so the heading will not repeat every page. However, I still need my produced file to contain headers. Is there a way to add a row of headers (not to the table itself) into the query that won't actually be considered a header when spooling? This is my code which works, it just doesn't contain headers when I set heading off
.
select a.col1 as name1,
a.col2 as name2,
b.col3 as name3
from tab1 a,
tab2 b
Thanks in advance
回答1:
you could always try something like:
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>;
ETA: If the column types returned by the main query aren't all strings, you'll have to explicitly convert them. Here is an example:
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
回答2:
You said you're spooling to a CSV file, so presumably the column spacing doesn't matter (and you have set colsep ,
already).
If so, you can use the SQL*Plus prompt command to fake a header, without needing a union:
prompt name1,name2,name3
select a.col1,
a.col2,
b.col3
from tab1 a,
tab2 b
Or a separate query, again without the union:
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
Again the values won't align with the real data columns, but for CSV you don't really care. (For CSV I usually explicitly concatenate the values with commas anyway, which removes a load of whitespace and makes the file smaller).
回答3:
You want to try:
set pages <number of rows you expect>
E.g.
set pages 1000
Another way around could be a UNION like so:
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
来源:https://stackoverflow.com/questions/31835109/trouble-creating-headers-using-spool-in-sqlplus