Question

I want to use spool functionality in Oracle 11g.

I want the entire output to be spooled into a file and a subset of the output to be spooled into a separate file.

In the below example I want temp_1.txt to contain data from A,B,C,D and E

In temp_2.txt I want data only for D.

sqlplus user/pass@inst

spool on temp_1.txt    
select * from A;
select * from B;
select * from C; 
spool on temp_2.txt
select * from D;
spool off temp_2.txt
select * from E;

exit;

Note:- Since this is very old legacy code I can't write a separate sqlplus session for D or re order the selects.

Was it helpful?

Solution

How about doing it all in the sqlplus script. The host commands will need to change if you ever run on a different system (ie. Microsoft Windows). But, they would be required to change in a shell script as well.

spool all_queries.txt
select * from A;
select * from B;
select * from C;
spool off

spool only_d_query.txt
select * from D;
spool off

host cat only_d_query.txt >>all_queries.txt

spool all_queries.txt append
select * from E;
spool off

OTHER TIPS

You can't do that. The SPOOL command only allows one open file at a time; your second command, which would be spool temp_2.txt (without the on) would close the first file before opening and starting to write to the second one. And off doesn't take any further parameters.

Usage: SPOOL { <file> | OFF | OUT }
where <file> is file_name[.ext] [CRE[ATE]|REP[LACE]|APP[END]]

One solution would be to spool the output of the statements to different files:

spool temp_1.txt
select * from A;
select * from B;
select * from C;
spool temp_2.txt
select * from D;
spool temp_3.txt
select * from E;
spool off

... and then combine all three files into one from the operating system to get your 'master' output file, while still retaining the D-only file separately. e.g.:

cat temp_2.txt >> temp_1.txt
cat temp_3.txt >> temp_1.txt
rm temp_3.txt`

Which leaves temp_1.txt and temp_2.txt with the content you wanted, if I've understood you correctly. Different method if you're on Windows, of course.

Alternatively you could run the queries in a PL/SQL block and use UTL_FILE to write the results to one or both of two open files. But that's a bit more work, and would write the files on the server - so you'd need permissions on a DIRECTORY object to write to, and access to the underlying filesystem directory that points to in order to retrieve the files.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top