Search code examples
sqloracle-databasesqlplussql-scripts

SQL query inside a SQL Script


I have a SQL script, which spools data to a file. Sample Existing SQL script:

whenever sqlerror exit failure rollback 
spool test.txt
set serveroutput on
select * from emp;
spool off
/

But, I would like to write a SQL query in this script before spooling data. I don't want to hardcode the name of the spooling file, so how could I get the file name from a table or lookup?

I want the code to be something like

var filename varchar2(30);
select fname into :filename from table where script = 'abcscript';
spool :filename
set serveroutput on
select * from emp;
spool off
/

Thanks.


Solution

  • COLUMN spool_file_name NEW_VALUE.spool_file_name NOPRINT 
    
    select fname spool_file_name 
     from table where script = 'abcscript'; 
    
    SPOOL &spool_file_name 
    
    SET ECHO ON 
    
     select * from emp ;
    
    SPOOL OFF 
    COLUMN spool_file_name CLEAR