 <p>SPOOL is a SQLPlus command, so you can not use it in a PlSQL block dynamically.</p> <p>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:</p> <pre><code>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 </code></pre> <p>This gives:</p> <pre><code>SQL&gt; sta C:\firstScript.sql Connected. set colsep | spool d:\filename.txt select 1, 2, 3 from dual; 1| 2| 3 ----------|----------|---------- 1| 2| 3 </code></pre> <p><strong>d:\filename.txt</strong>:</p> <pre><code> 1| 2| 3 ----------|----------|---------- 1| 2| 3 </code></pre>