问题
I have a scenario where we generate spool based on condition.
The spool should generate only if user types y.
column col noprint new_value elcm_script
select decode(lower('&gen'),'y','C:\ELCM.SQL','n', 'null') col from dual;
SPOOL c:\ELCM_DETAILS.SPL
@&elcm_script
spool off
In the above it will generate spool file even if user type n like error reading file.. How to stop generating the spool if n.or how to remove spool which is generated/
回答1:
If you can put this controlling section into its own script, e.g. elcm_ctl.sql
, you could make that:
accept run_it char format a1 prompt "Run the script?"
set termout off
whenever sqlerror exit success rollback
exec if upper(nvl('&run_it', 'N')) != 'Y' then raise no_data_needed; end if;
whenever sqlerror continue
spool c:\elcm.sql
select 'select sysdate from dual;' from dual;
spool off
set termout on
spool c:\elcm_details.spl
@c:\elcm.sql
spool off
The accept command is a bit neater than relying on substitution prompts, in my opinion, and is somewhat self-documenting. This prompts the user with the specified string, rather than just 'gen'
. (In SQL*Plus you can extend this and force the user to put in a single character, re-prompting if they put in anything longer; and default to 'N' if they just press return without entering anything. But SQL Developer only supports a subset of the functionality).
Then a small anonymous block throws an exception - doesn't really matter which one - if the entered variable value is not 'y'
or 'Y'
. While it's doing that I've set termout off so you don't see the actual exception. And I've used whenever sqlerror to make the script exit when that exception is raised, so whatever comes later is not run. That is everything else in the control script, not just the next query, but you could have several sub-scripts if you needed to be more flexible.
But in SQL Developer, termout
only works as expected when you run via @
. If you run the contents of elcm_ctl.sql
directly from the SQL Worksheet you'll see the exception being raised, which is a bit ugly. So instead save that control script and in an empty worksheet just do:
@c:\elcm_ctl.sql
Execute that worksheet as a script and it will prompt you; if you enter 'Y'
you'll see the output of the script in the script output window (unless you leave set termout off
in the control script), and it will create the spool file. If you enter anything else then it won't run the elcm.sql
file, won't show anything in the script output window, and won't create a spool file.
来源:https://stackoverflow.com/questions/24446924/condition-based-spool-generation-in-oracle-sql-script