SQLPlus dynamic spool filename

Seth De picture Seth De · Oct 5, 2016 · Viewed 15.7k times · Source

i have an Oracle db and i want to export data to a file.However filename, extension and separator will take value from table. The problem is that i can't use the values from table. Could you suggest me a way to do it? Or if i can do this with batch?

Table(id, path, filename, extension, separator)

script.sql

conn ....
variable fullpath varchar2(20);
variable filename varchar2(10);  
variable extension varchar2(5);  
variable sep varchar2(1);

begin
  select filename, path, extension,separator
  into :filename, :fullpath, :extension, :sep
  from Table;
end;
/

set separator sep

spool fullpath||filename||'.'||extension;
... select queries...
spool off;

Regards

Answer

Aleksej picture Aleksej · Oct 5, 2016

SPOOL is a SQLPlus command, so you can not use it in a PlSQL block dynamically.

One way could be creating at runtime a second script, dynamically built based on your query, and then run it to do the job. For example:

conn ...
set serveroutput on
set feedback off
variable fullpath varchar2(20);
variable filename varchar2(10);  
variable extension varchar2(5);  
variable sep varchar2(1);
/* spool to a fixed file, that will contain your dynamic script */
spool d:\secondScript.sql
begin
  select 'filename', 'd:\', 'txt', '|'
  into :filename, :fullpath, :extension, :sep
  from dual;

  /* write the second script */

  dbms_output.put_line('set colsep ' || :sep);
  dbms_output.put_line('spool ' || :fullpath || :filename || '.' || :extension);
  dbms_output.put_line('select 1, 2, 3 from dual;');
  dbms_output.put_line('spool off');
end;
/
spool off  

/* run the second script */
@d:\secondscript.sql

This gives:

SQL> sta C:\firstScript.sql
Connected.
set colsep |
spool d:\filename.txt
select 1, 2, 3 from dual;

         1|         2|         3
----------|----------|----------
         1|         2|         3

d:\filename.txt:

         1|         2|         3                                                
----------|----------|----------                                                
         1|         2|         3